This is a premium problem. We're working on making it available for free soon.
Use these hints if you're stuck. Try solving on your own first.
To find the minimum cost to make nums non-decreasing, use a max heap that contains all of the elements that you have seen so far.
If the largest number in the heap is greater than the current number, calculate the cost to make the two numbers equal. Then, in the heap, replace the largest number with the current number.
Now that we have found the minimum cost to make nums non-decreasing, we can set every nums[i] to -nums[i] and do the same process to find the minimum cost to make nums non-increasing.
Solutions for this premium problem will be available for free soon.
Browse Free ProblemsWatch expert explanations and walkthroughs
Practice problems asked by these companies to ace your technical interviews.
Explore More ProblemsJot down your thoughts, approach, and key learnings
The problem allows the array to become either non-decreasing or non-increasing. Since the optimal transformation may differ between the two, solving both variants and taking the smaller cost ensures the correct minimum result.
Yes, variations of this problem appear in technical interviews because it tests dynamic programming intuition, greedy reasoning, and cost optimization. It is considered a challenging problem suitable for advanced interview preparation.
A common optimal strategy combines dynamic programming or a greedy heap-based technique. The idea is to enforce a non-decreasing sequence while minimizing adjustment costs, then repeat the process for the non-increasing case and take the minimum result.
Priority queues (heaps) are often used in greedy solutions to maintain order while correcting violations efficiently. Dynamic programming solutions may also rely on sorted arrays or coordinate compression to limit candidate values.