Minimum increment / decrement to make array non | C # code to count the change required to convert the array into non - increasing array ; min heap ; Here in the loop we will check that whether the upcoming element of array is less than top of priority queue . If yes then we calculate the difference . After that we will remove that element and push the current element in queue . And the sum is incremented by the value of difference ; Driver code
using System ; using System . Collections . Generic ; class GFG { static int DecreasingArray ( int [ ] a , int n ) { int sum = 0 , dif = 0 ; List < int > pq = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( pq . Count > 0 && pq [ 0 ] < a [ i ] ) { dif = a [ i ] - pq [ 0 ] ; sum += dif ; pq . RemoveAt ( 0 ) ; } pq . Add ( a [ i ] ) ; pq . Sort ( ) ; } return sum ; } static void Main ( ) { int [ ] a = { 3 , 1 , 2 , 1 } ; int n = a . Length ; Console . Write ( DecreasingArray ( a , n ) ) ; } }