Find the maximum possible value of last element of the Array | C ++ program to find the maximum possible value of last element of the array ; Function to find the maximum possible value of last element of the array ; Traverse for all element ; Find the distance ; If moves less than distance then we can not move this number to end ; How many number we can move to end ; Take the minimum of both of them ; Increment in the end ; Remove taken moves ; Return the last element ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxValue ( int arr [ ] , int n , int moves ) { for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] > 0 ) { int distance = n - 1 - i ; if ( moves < distance ) break ; int can_take = moves / distance ; int take = min ( arr [ i ] , can_take ) ; arr [ n - 1 ] += take ; moves -= take * distance ; } } return arr [ n - 1 ] ; } int main ( ) { int arr [ ] = { 2 , 3 , 0 , 1 } ; int M = 5 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxValue ( arr , N , M ) ; return 0 ; }