Minimum increments to convert to an array of consecutive integers | Function that return true if the required array can be generated with m as the last element ; Build the desired array ; Check if the given array can be converted to the desired array with the given operation ; Function to return the minimum number of operations required to convert the given array to an increasing AP series with common difference as 1 ; Apply Binary Search ; If array can be generated with mid as the last element ; Current ans is mid ; Check whether the same can be achieved with even less operations ; Build the desired array ; Calculate the number of operations required ; Return the number of operations required ; Driver code
function check ( m , n , arr ) { var desired = Array ( n ) ; for ( var i = n - 1 ; i >= 0 ; i -- ) { desired [ i ] = m ; m -- ; } for ( var i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > desired [ i ] desired [ i ] < 1 ) { return false ; } } return true ; } function minOperations ( arr , n ) { var start = arr [ n - 1 ] ; var end = arr . reduce ( ( a , b ) => Math . max ( a , b ) ) + n ; var max_arr = 0 ; while ( start <= end ) { var mid = parseInt ( ( start + end ) / 2 ) ; if ( check ( mid , n , arr ) ) { max_arr = mid ; end = mid - 1 ; } else { start = mid + 1 ; } } var desired = Array ( n ) ; for ( var i = n - 1 ; i >= 0 ; i -- ) { desired [ i ] = max_arr ; max_arr -- ; } var operations = 0 ; for ( var i = 0 ; i < n ; i ++ ) { operations += ( desired [ i ] - arr [ i ] ) ; } return operations ; } var arr = [ 4 , 4 , 5 , 5 , 7 ] ; var n = arr . length ; document . write ( minOperations ( arr , n ) ) ;