Friday, June 3, 2022

2263. Make Array Non-decreasing or Non-increasing | Hard level

 Example 1:

Input: nums = [3,2,4,5,0]
Output: 4
Explanation:
One possible way to turn nums into non-increasing order is to:
- Add 1 to nums[1] once so that it becomes 3.
- Subtract 1 from nums[2] once so it becomes 3.
- Subtract 1 from nums[3] twice so it becomes 3.
After doing the 4 operations, nums becomes [3,3,3,3,0] which is in non-increasing order.
Note that it is also possible to turn nums into [4,4,4,4,0] in 4 operations.
It can be proven that 4 is the minimum number of operations needed.

15 minutes thinking

  1. Non-decreasing or non-increasing? 
  2. +1 or -1
  3. How to find minimum number? Brute force? 
  4. If the minimum number is 4, how to find the first one - increase one or decrease one? 
  5. Data structure? 
  6. Algorithm? 
  7. DFS? 
  8. Work on example: [3,2,4,5,0]

No comments:

Post a Comment