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
iwhere0 <= i < nums.length - Set
nums[i]tonums[i] + 1ornums[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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code