Minimum Replacements to Sort the Array Problem
#2366
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2366.
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 replacenums[1]with2and4and convertnumsto[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 <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Greedy From the Right
Go from right to left, keeping mx, the largest value the current element may have so that the suffix is non-decreasing. Start with mx = nums[n - 1].
- If
nums[i] <= mx, nothing to do; the new limit isnums[i]. - Otherwise
nums[i]must be split intok = ceil(nums[i] / mx)parts, which costsk - 1operations. To leave the largest possible limit for the elements on the left, make the parts as equal as possible; the smallest part isfloor(nums[i] / k), which becomes the newmx.
Complexity: O(n) time and O(1) space.
class Solution:
def minimumReplacement(self, nums: List[int]) -> int:
ans = 0
n = len(nums)
mx = nums[-1]
for i in range(n - 2, -1, -1):
if nums[i] <= mx:
mx = nums[i]
continue
k = (nums[i] + mx - 1) // mx
ans += k - 1
mx = nums[i] // k
return ans