Maximize Sum Of Array After K Negations — LeetCode 1005 Python Solution

EasyGreedyArraySorting
Problem
#1005
Pattern
Greedy
Reading time
3 min

The problem

Given an integer array nums and an integer k, modify the array in the following way: choose an index i and replace nums[i] with -nums[i]. You should apply this process exactly k times.

Example

Input
nums = [4,2,3], k = 1
Output
5
Explanation
Choose index 1 and nums becomes [4,-2,3].

Python solution

Python
class Solution:
    def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:
        cnt = Counter(nums)
        for x in range(-100, 0):
            if cnt[x]:
                m = min(cnt[x], k)
                cnt[x] -= m
                cnt[-x] += m
                k -= m
                if k == 0:
                    break
        if k & 1 and cnt[0] == 0:
            for x in range(1, 101):
                if cnt[x]:
                    cnt[x] -= 1
                    cnt[-x] += 1
                    break
        return sum(x * v for x, v in cnt.items())

Complexity

MeasureComplexity
TimeO(n + M)
SpaceO(M) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1005. Maximize Sum Of Array After K Negations is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1005. Maximize Sum Of Array After K Negations?
LeetCode 1005. Maximize Sum Of Array After K Negations is rated Easy on LeetCode.
What is the time complexity of LeetCode 1005. Maximize Sum Of Array After K Negations?
The Python solution on this page runs in O(n + M).
What is the space complexity of LeetCode 1005. Maximize Sum Of Array After K Negations?
The Python solution on this page uses O(M) auxiliary space.
What topics does LeetCode 1005. Maximize Sum Of Array After K Negations cover?
LeetCode 1005. Maximize Sum Of Array After K Negations is tagged Greedy, Array and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview