Find maximum sum taking every Kth element in the array | Python 3 implementation of the approach ; 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
import sys NEW_LINE def maxSum ( arr , n , K ) : NEW_LINE INDENT maximum = - sys . maxsize - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sumk = 0 NEW_LINE for j in range ( i , n , K ) : NEW_LINE INDENT sumk = sumk + arr [ j ] NEW_LINE DEDENT maximum = max ( maximum , sumk ) NEW_LINE DEDENT return maximum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 6 , 4 , 7 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE K = 2 NEW_LINE print ( maxSum ( arr , n , K ) ) NEW_LINE DEDENT