Leetcode 1047 Solution

This article provides solution to leetcode question 1047 (maximize-sum-of-array-after-k-negations)

https://leetcode.com/problems/maximize-sum-of-array-after-k-negations

Solution

class Solution(object): def largestSumAfterKNegations(self, A, K): """ :type A: List[int] :type K: int :rtype: int """ heap = []
s = 0 for a in A: s += a heapq.heappush(heap, a)
for _ in range(K): a = heapq.heappop(heap) heapq.heappush(heap, -a) s -= 2 * a
return s