Leetcode 1005. Maximize Sum Of Array After K Negations
class Solution(object): def largestSumAfterKNegations(self, A, K): """ :type A: List[int] :type K: int :rtype: int """ have_zero = False negative = [] positive = [] for a in A: if a < 0: negative.append(a) elif a == 0: have_zero = True else: positive.append(a) neg_size = len(negative) if neg_size > 0: negative.sort() for i in range(neg_size): if K > 0: negative[i] = -negative[i] K -= 1 if (K > 0) and (K % 2 == 1) and (not have_zero): positive.sort() if len(positive) > 0: sub = min(positive[0], negative[neg_size - 1]) else: sub = negative[neg_size - 1] return sum(negative) + sum(positive) - 2 * sub return sum(negative) + sum(positive) elif have_zero: return sum(positive) else: K = K % 2 if K == 1: positive.sort() positive[0] = -positive[0] return sum(positive) else: return sum(positive)