Find the Maximum Alternate Subsequence Sum from a given array | Function to find maximum alternating subsequence sum ; initialize sum to 0 ; calculate the sum ; return the final result ; array initiaisation ; length of array
def maxAlternatingSum ( arr , n ) : NEW_LINE INDENT max_sum = 0 NEW_LINE i = 0 NEW_LINE while i < n : NEW_LINE INDENT current_max = arr [ i ] NEW_LINE k = i NEW_LINE while k < n and ( ( arr [ i ] > 0 and arr [ k ] > 0 ) or ( arr [ i ] < 0 and arr [ k ] < 0 ) ) : NEW_LINE INDENT current_max = max ( current_max , arr [ k ] ) NEW_LINE k += 1 NEW_LINE DEDENT max_sum += current_max NEW_LINE i = k NEW_LINE DEDENT return max_sum NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , - 1 , - 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxAlternatingSum ( arr , n ) ) NEW_LINE