Minimum increment / decrement to make array non | Javascript 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
function DecreasingArray ( a , n ) { var sum = 0 , dif = 0 ; var pq = [ ] ; for ( var i = 0 ; i < n ; i ++ ) { if ( pq . length != 0 && pq [ pq . length - 1 ] < a [ i ] ) { dif = a [ i ] - pq [ pq . length - 1 ] ; sum += dif ; pq . pop ( ) ; } pq . push ( a [ i ] ) ; pq . sort ( ( a , b ) => b - a ) ; } return sum ; } var a = [ 3 , 1 , 2 , 1 ] ; var n = a . length ; document . write ( DecreasingArray ( a , n ) ) ;