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 replacenums[1]
with2
and4
and convertnums
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
Intuition
Approach
- In the first step we make out prev=3
- Now we iterate backwards, now our value becomes 9 which is more than our prev value, so we have to break this in such a way that the max element in this is less than or equal to prev element and min element must as greater as possible. Why min element must be greater becauase we are following greedy approach we can easily solve further for elements.
- How many splits we can do is the question?
9 -> 3 3 3 //to satisfy the condition.
split-1:9->6 3
split-2:9->3 3 3
Total Splits = Math.ceil(9/3) - 1 //becuase you have splitted it twice.
- Next task is what is the min value we got after splitting
splits = 2
value = 9/(2+1) = 3
Now prev = value
- If out current value is simply smaller than prev element then we can assign it to the prev = currElement and move forward
Complexity
Time complexity:
O(N)Space complexity:
O(1)
Comments
Post a Comment