475. Make Array Non decreasing or Non increasing
You are given a 0-indexed integer array nums. In one operation, you can:
- Choose an index i in the range 0 <= i < nums.length
- Set nums[i] to nums[i] + 1 or nums[i] - 1
Return the minimum number of operations to make nums non-decreasing or non-increasing.
Example 1:
Input : nums = [3, 5, 1, 2]
Output : 3
Explanation :
One possible way to turn nums into non-increasing order is to:
- Subtract 1 from nums[1] twice so it becomes 3.
- Add 1 to nums[2] once so it becomes 2.
After doing the 3 operations, nums becomes [3,3,2,2] which is in non-increasing order.
It can be proven that 3 is the minimum number of operations needed.
Example 2:
Input : nums = [5, 4, 3, 2, 1]
Output : 0
Explanation :
nums is already in non-decreasing order, so no operations are needed and we return 0.
Now Your Turn!
Pick the correct output for the given inputInput : nums = [5, 1, 2, 7, 0]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= nums.length <= 1000
- 0 <= nums[i] <= 1000