Python 1005.py
class Solution:
def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:
heapify(nums)
for _ in range(k):
heappush(nums, -heappop(nums))
return sum(nums)
Difficulty
and has an acceptance rate of about 54% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of maximizing the sum of an integer array after performing exactly k negations. The core idea is to repeatedly flip the smallest element (in terms of value) because changing a negative number to positive yields the greatest immediate increase in the total sum. A min-heap is employed to efficiently retrieve and update the smallest element after each negation.
Key Steps
The algorithm can be broken down into three distinct operations.
Heap Construction
heapify(nums)
The heapify call transforms the input list nums into a min-heap in place. After this step the smallest element of the array resides at the root of the heap, enabling constant-time access for the subsequent negation loop.
Repeated Negation Loop
for _ in range(k):
heappush(nums, -heappop(nums))
Inside the loop the smallest element is removed with heappop, its sign is inverted, and the resulting value is inserted back with heappush. Because the heap property is maintained after each insertion, the next iteration again operates on the current smallest element. This process repeats exactly k times, guaranteeing that the prescribed number of sign changes is applied.
Final Summation
return sum(nums)
After all negations have been performed, the built-in sum function aggregates the values in the heap, which now represents the final array configuration. The returned integer is the maximum achievable sum under the given constraints.
Edge Cases Handled
The algorithm naturally accommodates several special input configurations without additional conditional logic.
When the array contains only non-negative numbers, the smallest element is zero or a positive value. Flipping a zero leaves the array unchanged, while flipping a positive number reduces the sum. Because the loop executes exactly k times, the code will repeatedly flip the smallest positive value, which may be the same element multiple times. This behavior correctly models the requirement that exactly k negations must occur, even if they are detrimental to the sum.
If the array consists entirely of negative numbers, the first k iterations will convert the most negative values to positive, each conversion increasing the total sum. When k exceeds the number of negative entries, the algorithm continues to flip the smallest (now possibly positive) element, effectively toggling its sign back and forth. This correctly reflects the scenario where extra negations must be applied after all negatives have been eliminated.
The presence of zeros is also covered. Zero is the smallest element in a heap containing non-negative numbers, and flipping zero has no effect. Consequently, if zeros exist and k remains after all beneficial flips, the loop will repeatedly process a zero, leaving the sum unchanged, which aligns with the problem’s constraints.
When k is zero, the loop body is never executed. The heap is built, but no modifications occur, and the original sum is returned directly.
Performance Optimizations
The use of an in-place heap construction via heapify eliminates the need for auxiliary data structures, reducing memory overhead. By maintaining the heap property throughout the negation loop, each sign change operates on the current minimal element without scanning the entire list, which would be costly for large inputs. The combination of heappop and heappush ensures that the heap remains balanced after each modification, allowing the algorithm to continue accessing the smallest element efficiently throughout all k iterations. This design leverages the strengths of the heap data structure to keep the overall execution swift even when the number of negations is large.
ELI5 - Simplified Explanation
Imagine a row of numbers sitting on a shelf. Some of these numbers are positive and some are negative, like a balance scale with weights on each side. The goal is to make the total sum of all these numbers as big as possible.
To do this, the computer looks at all the numbers and finds the smallest one, which is usually the one that makes the sum go down the most if it is a negative number. Once the computer picks that smallest number, it flips it. If it was a minus five, it becomes a five. If it was a tiny positive number, it might become negative.
The computer keeps doing this flipping trick exactly as many times as asked. Each time, the computer quickly checks to find the new smallest number again so it always knows which one to change. After finishing all the flips, the computer looks at all the numbers left on the shelf and adds them up to see what the final total is.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 935: Knight Dialer
- problem 1029: Two City Scheduling
- problem 1769: Minimum Number of Operations to Move All Balls to Each Box
- problem 2080: Range Frequency Queries
- problem 793: Preimage Size of Factorial Zeroes Function
- problem 878: Nth Magical Number
- problem 902: Numbers At Most N Given Digit Set
- problem 1751: Maximum Number of Events That Can Be Attended II
- problem 1793: Maximum Score of a Good Subarray
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality