1005. K 次取反后最大化的数组和

exiaohu 于 2021-12-03 发布

题目链接:1005. K 次取反后最大化的数组和

import heapq
from typing import List


class Solution:
    def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:
        ans, q = sum(nums), []
        for num in nums:
            heapq.heappush(q, num)

        for _ in range(k):
            item = heapq.heappop(q)
            ans -= item * 2
            heapq.heappush(q, -item)

        return ans