Maximize the last Array element as per the given conditions | Function to find the maximum possible value that can be placed at the last index ; Sort array in ascending order ; If the first element is not equal to 1 ; Traverse the array to make difference between adjacent elements <= 1 ; Driver Code
function maximizeFinalElement ( arr , n ) { arr . sort ( ( a , b ) => a - b ) ; if ( arr [ 0 ] != 1 ) arr [ 0 ] = 1 ; for ( let i = 1 ; i < n ; i ++ ) { if ( arr [ i ] - arr [ i - 1 ] > 1 ) { arr [ i ] = arr [ i - 1 ] + 1 ; } } return arr [ n - 1 ] ; } let n = 4 ; let arr = [ 3 , 1 , 3 , 4 ] ; let max = maximizeFinalElement ( arr , n ) ; document . write ( max ) ;