Minimum range increment operations to Sort an array | Function to find minimum range increments to sort an array ; If current element is found greater than last element Increment all terms in range i + 1 to n - 1 ; Minimum in range i to n - 1 ; Driver Code
function minMovesToSort ( arr , n ) { var moves = 0 ; var i , mn = arr [ n - 1 ] ; for ( i = n - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] > mn ) moves += arr [ i ] - mn ; mn = arr [ i ] ; } return moves ; } var arr = [ 3 , 5 , 2 , 8 , 4 ] ; var n = arr . length ; document . write ( minMovesToSort ( arr , n ) ) ;