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 ; Initialize the sum array with zero ; Iterate from the right ; Update the sum starting at the current element ; Update the maximum so far ; Driver code
def maxSum ( arr , n , K ) : NEW_LINE INDENT maximum = - 2 ** 32 ; NEW_LINE sum = [ 0 ] * n NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( i + K < n ) : NEW_LINE INDENT sum [ i ] = sum [ i + K ] + arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT sum [ i ] = arr [ i ] ; NEW_LINE DEDENT maximum = max ( maximum , sum [ i ] ) NEW_LINE DEDENT return maximum ; NEW_LINE DEDENT arr = [ 3 , 6 , 4 , 7 , 2 ] NEW_LINE n = len ( arr ) ; NEW_LINE K = 2 NEW_LINE print ( maxSum ( arr , n , K ) ) NEW_LINE