Problem Description
Given a 0-indexed integer array nums, determine the minimum number of operations required to transform it into either a non-decreasing or non-increasing sequence. In one operation, you can choose any index i and either add 1 or subtract 1 from nums[i].
Key Insights
- The problem is equivalent to finding a target sequence (either non-decreasing or non-increasing) that minimizes the total adjustments (absolute differences).
- We can use dynamic programming (DP) to compute the minimal cost for adjusting the array.
- For the non-decreasing case, each element's chosen value must be at least the value chosen for the previous element.
- For non-increasing order, each element's chosen value must be at most the previous one.
- By iterating over all possible target values (0 through 1000) for each index and using prefix (or suffix) minimums to speed up state transitions, we can obtain the solution efficiently.
- Compute the result for both monotonic orders and return the smaller one.
Space and Time Complexity
Time Complexity: O(n * M), where n is the length of nums and M is 1001 (the range of possible values). Space Complexity: O(M), by using rolling arrays to update the DP state.
Solution
We solve the problem with two DP routines: one for forming a non-decreasing sequence and one for a non-increasing sequence. For each index i and for every possible new value v (0 ≤ v ≤ 1000), the DP state records the minimal cost to adjust nums[0...i] so that the iᵗʰ element becomes v and the monotonic property is satisfied. For the non-decreasing case, we enforce that the previous value is at most v; for non-increasing, the previous value is at least v. By precomputing prefix (or suffix) minima for each state transition, we efficiently update the DP states.
Code Solutions
Below are implementations in Python, JavaScript, C++, and Java, with detailed line-by-line comments.