Leetcode 1047 Solution
This article provides solution to leetcode question 1047 (maximize-sum-of-array-after-k-negations)
Access this page by simply typing in "lcs 1047" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
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