↓Skip to main content
  1. LeetCode/

LeetCode 1005: Maximize Sum Of Array After K Negations

·1 min· ·
LeetCode Easy Array Greedy Sorting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-27

  • Submissions: Runtime Error → Accepted

Approach
#

Greedy (Greedy Template 1): negating the current minimum increases the sum the most. A min-heap doing k rounds of heappop and heappush(-x) suffices, O(k log n). Alternatively sort, flip negatives from smallest up, and if an odd number of flips remain, flip the value with the smallest absolute value once more.

My Attempts
#

Attempt 1 had an indentation error (Runtime Error); the same min-heap code then passed.

Solution
#

class Solution:
    def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:
        heapq.heapify(nums)
        for _ in range(k):
            heapq.heappush(nums, -heapq.heappop(nums))
        return sum(nums)

Complexity
#

Time O(n + k log n), space O(1).

Mistakes to Avoid
#

  • One value may be negated many times; once the minimum is positive it flips back and forth, which the heap handles naturally.

Interview Explanation
#

Negating the minimum gains the most each time, so I do it k times with a min-heap and sum at the end; once the minimum is positive the same value flips back and forth, so only parity matters. Time O(n + k log n).

Related

LeetCode 561: Array Partition
·1 min
LeetCode Easy Array Greedy Sorting Counting-Sort
LeetCode 561 note: sort and pair neighbors; each pair’s minimum is the element at an even index, so sum those
LeetCode 455: Assign Cookies
·2 mins
LeetCode Easy Array Two-Pointers Greedy Sorting
LeetCode 455 note: sort children and cookies, satisfying the least greedy child with the smallest cookie that suffices; each pointer walks once
LeetCode 1013: Partition Array Into Three Parts With Equal Sum
·2 mins
LeetCode Easy Array Greedy
LeetCode 1013 note: the total must be divisible by 3; accumulate from the left, cutting whenever the running sum hits total / 3, and succeed with at least 3 pieces
LeetCode 977: Squares of a Sorted Array
·1 min
LeetCode Easy Array Two-Pointers Sorting
LeetCode 977 note: the largest squares are at the two ends, so compare the ends with two pointers and fill the result from the back
LeetCode 905: Sort Array By Parity
·1 min
LeetCode Easy Array Two-Pointers Sorting
LeetCode 905 note: a write pointer swaps even numbers to the front, just like move zeroes
LeetCode 922: Sort Array By Parity II
·1 min
LeetCode Easy Array Two-Pointers Sorting
LeetCode 922 note: pointers i over even slots and j over odd slots, each stepping by two; when slot i holds an odd number, move j to a misplaced even and swap