1005. Maximize Sum Of Array After K Negations

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

solution

class Solution:
    def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:
        nums.sort()

        n = 0
        for i, num in enumerate(nums):
            if n <= k-1 and num < 0:
                nums[i] = -nums[i]
                n += 1
            else:
                break
        
        if k > n:
            if (k - n) % 2 == 0:
                return sum(nums)
            else:
                nums.sort()
                nums[0] = -nums[0]
                return sum(nums)
        else:
            return sum(nums)

时间复杂度:O() 空间复杂度:O()

Last updated