Longest alternating subsequence with maximum sum | Set 2 | Function to check the sign of the element ; Function to calculate and return the maximum sum of longest alternating subsequence ; Iterate through the array ; Stores the first element of a sequence of same sign ; Traverse until an element with opposite sign is encountered ; Update the maximum ; Update the maximum sum ; Update i ; Return the maximum sum ; Driver Code
def sign ( x ) : NEW_LINE INDENT if ( x > 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT def findMaxSum ( arr , size ) : NEW_LINE INDENT max_sum = 0 NEW_LINE i = 0 NEW_LINE while i < size : NEW_LINE INDENT pres = arr [ i ] NEW_LINE j = i NEW_LINE while ( j < size and ( sign ( arr [ i ] ) == sign ( arr [ j ] ) ) ) : NEW_LINE INDENT pres = max ( pres , arr [ j ] ) NEW_LINE j += 1 NEW_LINE DEDENT max_sum = max_sum + pres NEW_LINE i = j - 1 NEW_LINE i += 1 NEW_LINE DEDENT return max_sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 2 , 8 , 3 , 8 , - 4 , - 15 , 5 , - 2 , - 3 , 1 ] NEW_LINE size = len ( arr ) NEW_LINE print ( findMaxSum ( arr , size ) ) NEW_LINE DEDENT