Problem 1005

Abstract / Summary

Given an array and a number of negations, flip signs to maximize the sum by first negating the smallest values.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
6 lines | 212 bytes | submitted November 27, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 54% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7.5 | μ = 6.50 | σ = 2.45

Complexity Analysis

Time: loglinear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
31 links | 18 authors | 8 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

10 solutions   November 27, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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