Find maximum sum taking every Kth element in the array | Function to return the maximum sum for every possible sequence such that a [ i ] + a [ i + k ] + a [ i + 2 k ] + ... + a [ i + qk ] is maximized ; Initialize the maximum with the smallest value ; Find maximum from all sequences ; Sum of the sequence starting from index i ; Update maximum ; Driver code
< ? php function maxSum ( $ arr , $ n , $ K ) { $ maximum = PHP_INT_MIN ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ sumk = 0 ; for ( $ j = $ i ; $ j < $ n ; $ j += $ K ) $ sumk = $ sumk + $ arr [ $ j ] ; $ maximum = max ( $ maximum , $ sumk ) ; } return $ maximum ; } $ arr = array ( 3 , 6 , 4 , 7 , 2 ) ; $ n = sizeof ( $ arr ) ; $ K = 2 ; echo maxSum ( $ arr , $ n , $ K ) ; ? >