Maximize every array element by repeatedly adding all valid i + a [ i ] th array element | C ++ program for the above approach ; Function to maximize value at every array index by performing given operations ; Traverse the array in reverse ; If the current index is a valid index ; Print the array ; Driver Code ; Given array ; Size of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( int arr [ ] , int N ) { int ans = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { int t = i ; if ( t + arr [ i ] < N ) { arr [ i ] += arr [ t + arr [ i ] ] ; } } for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << ' ▁ ' ; } } int main ( ) { int arr [ ] = { 1 , 2 , 7 , 1 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maxSum ( arr , N ) ; return 0 ; }