[LeetCode] Make Array Non-decreasing or Non-increasing

2263. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
int helper(vector<int>& A, bool inc) {
int res = 0, n = A.size();
priority_queue<int> pq;
for(int i = inc ? 0 : n - 1; 0 <= i and i < n; i += inc ? 1 : -1) {
if(!pq.empty() and pq.top() > A[i]) {
res += pq.top() - A[i]; pq.pop();
pq.push(A[i]);
}
pq.push(A[i]);
}
return res;
}
public:
int convertArray(vector<int>& nums) {
return min(helper(nums, true), helper(nums, false));
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/08/PS/LeetCode/make-array-non-decreasing-or-non-increasing/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.