Make Array Non-decreasing or Non-increasing - Problem

You are given a 0-indexed integer array nums. Your goal is to transform this array into either a non-decreasing (ascending) or non-increasing (descending) sequence using the minimum number of operations.

In each operation, you can:

  • Choose any index i where 0 <= i < nums.length
  • Set nums[i] to nums[i] + 1 or nums[i] - 1

Return the minimum number of operations needed to make nums either non-decreasing or non-increasing.

Example: For array [3, 2, 4, 5, 1], you could make it non-decreasing [1, 2, 3, 4, 5] or non-increasing [5, 4, 3, 2, 1]. The challenge is finding which transformation requires fewer operations.

Input & Output

example_1.py โ€” Basic Case
$ Input: [3, 2, 4, 5, 1]
โ€บ Output: 4
๐Ÿ’ก Note: To make non-decreasing: [1,2,3,4,5] costs 7 operations. To make non-increasing: [5,4,3,2,1] costs 4 operations. Choose the minimum: 4.
example_2.py โ€” Already Sorted
$ Input: [1, 2, 3, 4]
โ€บ Output: 0
๐Ÿ’ก Note: Array is already non-decreasing, so 0 operations needed.
example_3.py โ€” Single Element
$ Input: [5]
โ€บ Output: 0
๐Ÿ’ก Note: Single element array is both non-decreasing and non-increasing by definition.

Constraints

  • 1 โ‰ค nums.length โ‰ค 103
  • 1 โ‰ค nums[i] โ‰ค 104
  • Each operation changes a number by exactly 1
  • Must choose either non-decreasing OR non-increasing (not mixed)

Visualization

Tap to expand
Array Transformation: Building Heights AnalogyOriginal Array: [3, 2, 4, 1]3241Irregular skylineNon-Decreasing: [1, 2, 3, 4]1234Cost: 7 operationsNon-Increasing: [3, 3, 3, 3]3333Cost: 3 operations โญDynamic Programming Approach:1. Define State: dp[position][last_value][direction] = min operations2. Recurrence: dp[i][v][d] = min over all valid next values w:|nums[i] - v| + dp[i+1][w][d]3. Base Case: dp[n][*][*] = 0 (end of array)4. Answer: min(dp[0][min_val][inc], dp[0][max_val][dec])Time: O(n ร— Rยฒ) where R = max - min, Space: O(n ร— R)๐ŸŽฏ Key Insight: Use DP to systematically explore both directions with memoization
Understanding the Visualization
1
Analyze Original
Look at current array values and determine range
2
Try Both Directions
Calculate cost for non-decreasing and non-increasing
3
Use Dynamic Programming
Build optimal solutions using memoization
4
Choose Minimum
Select the direction requiring fewer operations
Key Takeaway
๐ŸŽฏ Key Insight: The problem has optimal substructure - the best way to transform a suffix depends on the chosen value for current position. Dynamic programming with memoization efficiently explores both non-decreasing and non-increasing possibilities.
Asked in
Google 35 Microsoft 28 Amazon 22 Meta 18
37.2K Views
Medium Frequency
~25 min Avg. Time
1.6K 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