Minimum increments to convert to an array of consecutive integers | Java implementation of the approach ; 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
import java . util . Arrays ; class GFG { static boolean check ( int m , int n , int arr [ ] ) { int [ ] desired = new int [ n ] ; for ( int i = n - 1 ; i >= 0 ; i -- ) { desired [ i ] = m ; m -- ; } for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > desired [ i ] desired [ i ] < 1 ) { return false ; } } return true ; } static int minOperations ( int arr [ ] , int n ) { int start = ( int ) arr [ n - 1 ] ; int end = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) + n ; int max_arr = 0 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( check ( mid , n , arr ) ) { max_arr = mid ; end = mid - 1 ; } else { start = mid + 1 ; } } int [ ] desired = new int [ n ] ; for ( int i = n - 1 ; i >= 0 ; i -- ) { desired [ i ] = max_arr ; max_arr -- ; } int operations = 0 ; for ( int i = 0 ; i < n ; i ++ ) { operations += ( desired [ i ] - arr [ i ] ) ; } return operations ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 4 , 5 , 5 , 7 } ; int n = arr . length ; System . out . println ( minOperations ( arr , n ) ) ; } }