# LeetCode 2263. Make Array Non-decreasing or Non-increasing

原题链接在这里：https://leetcode.com/problems/make-array-non-decreasing-or-non-increasing/description/

题目：

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,2,4,5,0] Output: 4 Explanation: One possible way to turn nums into non-increasing order is to: - Add 1 to nums[1] once so that it becomes 3. - Subtract 1 from nums[2] once so it becomes 3. - Subtract 1 from nums[3] twice so it becomes 3. After doing the 4 operations, nums becomes [3,3,3,3,0] which is in non-increasing order. Note that it is also possible to turn nums into [4,4,4,4,0] in 4 operations. It can be proven that 4 is the minimum number of operations needed.

Example 2:

Input: nums = [2,2,3,4] Output: 0 Explanation: nums is already in non-decreasing order, so no operations are needed and we return 0.

Example 3:

Input: nums = [0] Output: 0 Explanation: nums is already in non-decreasing order, so no operations are needed and we return 0.

Constraints:

`1 <= nums.length <= 1000`

`0 <= nums[i] <= 1000`

Follow up: Can you solve it in `O(n*log(n))`

time complexity?

题解：For non-increasing is equal to reverse num with non-decreasing, thus we only need to think about non-decreasing going from left to right.

For an array, e.g. 2, 6, 8, 5. We need minimum move 3 to make 8 and 5 equal. they could be [5, 5], [6, 6], [7, 7] or [8, 8]. Thus this bundle range is [5, 8] with 3 moves.

We choose lowest bound 5 as it is easy for the new number. But the previous number is 6. Actually that is a range, thus we know it is no charge to bump it.

Now array is 2, 6, 5, 5 with 3 moves.

If we have a new number 4, now we need to using the current maximum 6 to bundle with new 4. It takes at least 2 moves and move bundle range from 4 to 6.

We also keeps the minimum range 4 as bundle.

Now array is 2, 4, 5, 5, 4.

Eventually we get the minimum move is 5. The acutally array could be 2, 5, 5, 5, 5.

Time Complexity: O(n * logn). n = nums.length.

Space: O(n).

AC Java:

1 class Solution { 2 public int convertArray(int[] nums) { 3 int res = minMove(nums); 4 reverse(nums); 5 res = Math.min(res, minMove(nums)); 6 return res; 7 } 8 9 private int minMove(int[] nums){ 10 PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); 11 int res = 0; 12 for(int num : nums){ 13 if(!maxHeap.isEmpty() && maxHeap.peek() > num){ 14 res += maxHeap.poll() - num; 15 maxHeap.add(num); 16 } 17 18 maxHeap.add(num); 19 } 20 21 return res; 22 } 23 24 private void reverse(int[] nums){ 25 int l = 0; 26 int r = nums.length - 1; 27 while(l < r){ 28 int temp = nums[l]; 29 nums[l] = nums[r]; 30 nums[r] = temp; 31 l++; 32 r--; 33 } 34 } 35 }