Maximize sum possible from an array by jumps of length i + K * arr [ i ] from any ith index | Function to find the maximum sum possible by jumps of length i + K * arr [ i ] from any i - th index ; Initialize an array dp [ ] ; Stores the maximum sum ; Iterate over the range [ N - 1 , 0 ] ; If length of the jump exceeds N ; Set dp [ i ] as arr [ i ] ; Otherwise , update dp [ i ] as sum of dp [ i + K * arr [ i ] ] and arr [ i ] ; Update the overall maximum sum ; Print the answer ; Driver Code
function maxSum ( arr , N , K ) { let dp = [ ] ; for ( let i = 0 ; i < N + 2 ; i ++ ) { dp [ i ] = 0 ; } let maxval = 0 ; for ( let i = N - 1 ; i >= 0 ; i -- ) { if ( ( i + K * arr [ i ] ) >= N ) { dp [ i ] = arr [ i ] ; } else { dp [ i ] = dp [ i + K * arr [ i ] ] + arr [ i ] ; } maxval = Math . max ( maxval , dp [ i ] ) ; } document . write ( maxval ) ; } let arr = [ 2 , 1 , 3 , 1 , 2 ] ; let N = arr . length ; let K = 3 ; maxSum ( arr , N , K ) ;