Try   HackMD

2366.Minimum Replacements to Sort the Array

tags: Hard Array Math Greedy

2366. Minimum Replacements to Sort the Array

題目描述

You are given a 0-indexed integer array nums. In one operation you can replace any element of the array with any two elements that sum to it.

  • For example, consider nums = [5,6,7]. In one operation, we can replace nums[1] with 2 and 4 and convert nums to [5,2,4,7].

Return the minimum number of operations to make an array that is sorted in non-decreasing order.

範例

Example 1:

Input: nums = [3,9,3]
Output: 2
Explanation: Here are the steps to sort the array in non-decreasing order:
- From [3,9,3], replace the 9 with 3 and 6 so the array becomes [3,3,6,3]
- From [3,3,6,3], replace the 6 with 3 and 3 so the array becomes [3,3,3,3,3]
There are 2 steps to sort the array in non-decreasing order. Therefore, we return 2.

Example 2:

Input: nums = [1,2,3,4,5]
Output: 0
Explanation: The array is already in non-decreasing order. Therefore, we return 0.

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109

解答

C#

從最後一個數字往前找,如果比上一個數字大代表需要被分割,

  • 最少分割次數就用 (目前數字 - 1)/上一個數字
  • 分割後,排在前面的數字要盡量大,所以平均分配,用 目前數字/分割區塊
  • 分割後,排在前面的數字變成下一輪的上一個數字
public class Solution { public long MinimumReplacement(int[] nums) { if (nums.Length == 1) return 0; int last = nums.Last(); long splitCount = 0; for (int i = nums.Length - 2; i >= 0; i--) { if (last == 1) { splitCount += nums[i] - 1; continue; } if (nums[i] <= last) { last = nums[i]; continue; } int splitTimes = (nums[i] - 1) / last; splitCount += splitTimes; last = nums[i] / (splitTimes + 1); } return splitCount; } }

JimAug 30, 2023

Reference

回到題目列表