![]() |
VOOZH | about |
Given an array arr[], find the minimum number of operations ( either incrementing or decrementing by 1) required to convert it into a non-increasing array.
Note: An element can be incremented or decremented any number of times (possibly zero) to achieve the non-increasing order.
Examples :
Input : arr[] = [3, 1, 2, 1]
Output : 1
Explanation : We can convert the array into [3, 1, 1, 1] by changing 3rd element of array i.e. 2 into its previous integer 1 in one step. Hence, only one step is required.Input : arr[] = [3, 1, 5, 1]
Output : 4
Explanation : We need to decrease 5 to 1 to make array sorted in non-increasing order. The final non-increasing array is [3, 1, 1, 1].Input : arr[] = [5, 5, 5, 5]
Output : 0
Table of Content
We recursively try all possible target values for each element (ranging from 0 to the previous elementβs value) and compute the cost of converting the current element to that value. Among all such configurations, we take the minimum cost. Since we explore all combinations, the time complexity is exponential, making this approach infeasible for large arrays.
1
The idea is to traverse the array from left to right while keeping track of the smallest value seen so far in a min-heap. If the current element exceeds the smallest value so far, then it is reduced and the difference is added to the total operations. This ensures the sequence stays non-increasing as we move forward, while making only the necessary adjustments.
1