Find maximum sum of subsequence after flipping signs of at most K elements in given Array | Function to calculate the max sum of subsequence ; Variable to store the max sum ; Sort the array ; Iterate over the array ; Flip sign ; Decrement k ; Traverse over the array ; Add only positive elements ; Return the max sum ; Driver Code ; Given array ; Variable to store number of flips are allowed ; Function call to find the maximum sum of subsequence
def maxSubseq ( arr , N , K ) : NEW_LINE INDENT sum = 0 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( K == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT arr [ i ] = - arr [ i ] NEW_LINE K -= 1 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 6 , - 10 , - 1 , 0 , - 4 , 2 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE print ( maxSubseq ( arr , N , K ) ) NEW_LINE DEDENT