Make Array Non-decreasing or Non-increasing - Problem

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.

Input & Output

Example 1 — Mixed Array
$ Input: nums = [3,1,4,2]
Output: 4
💡 Note: Transform to non-decreasing [1,1,3,3]: |3-1| + |1-1| + |4-3| + |2-3| = 2 + 0 + 1 + 1 = 4 operations
Example 2 — Already Sorted
$ Input: nums = [1,2,3,4]
Output: 0
💡 Note: Array is already non-decreasing, so no operations needed
Example 3 — Reverse Order
$ Input: nums = [5,4,3,2,1]
Output: 0
💡 Note: Array is already non-increasing, so no operations needed

Constraints

  • 1 ≤ nums.length ≤ 300
  • 1 ≤ nums[i] ≤ 100

Visualization

Tap to expand
Make Array Non-decreasing or Non-increasing INPUT nums = [3, 1, 4, 2] 3 i=0 1 i=1 4 i=2 2 i=3 Current Order (disordered) 3 1 4 2 ALGORITHM STEPS 1 Try Non-decreasing Target: [1,1,2,2] or [2,2,2,2] Cost = |3-2|+|1-2|+|4-2|+|2-2| = 1+1+2+0 = 4 ops 2 Try Non-increasing Target: [3,3,3,2] or [4,4,4,2] Cost = |3-3|+|1-3|+|4-3|+|2-2| = 0+2+1+0 = 3 ops (partial) 3 DP with LIS Longest Increasing Subseq Keep max elements unchanged Adjust rest with min cost 4 Compare Both Non-decreasing cost: 4 Non-increasing cost: 4 min(4, 4) = 4 Optimal: [2,2,2,2] non-decreasing FINAL RESULT Optimal Array: [2, 2, 2, 2] 2 2 2 2 Operations Breakdown: 3 --> 2: 1 operation 1 --> 2: 1 operation 4 --> 2: 2 operations 2 --> 2: 0 operations Total: 4 operations Output 4 [OK] Non-decreasing achieved! Key Insight: The problem requires finding minimum operations to make array monotonic (either non-decreasing OR non-increasing). Use DP with coordinate compression: map values to ranks, then find LIS/LDS. The answer is n minus the longest monotonic subsequence length, minimizing total adjustment cost. Time: O(n log n) TutorialsPoint - Make Array Non-decreasing or Non-increasing | Optimal Solution
Asked in
Google 25 Amazon 18 Microsoft 15
15.4K Views
Medium Frequency
~35 min Avg. Time
680 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen