Maximize the last Array element as per the given conditions | C ++ Program to implement the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximizeFinalElement ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; if ( arr [ 0 ] != 1 ) arr [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] - arr [ i - 1 ] > 1 ) { arr [ i ] = arr [ i - 1 ] + 1 ; } } return arr [ n - 1 ] ; } int main ( ) { int n = 4 ; int arr [ ] = { 3 , 1 , 3 , 4 } ; int max = maximizeFinalElement ( arr , n ) ; cout << max ; return 0 ; }