Maximize Sum Of Array After K Negations in Python

Given an array of integers, we need to maximize the sum by negating exactly K elements. We can choose any element and replace it with its negative value, repeating this process K times.

The strategy is to first negate all negative numbers (since negating them increases the sum), then handle remaining negations optimally.

Algorithm

The approach involves these steps:

  • Sort the array to process negative numbers first

  • Negate negative numbers until K operations are exhausted or no negatives remain

  • If K operations remain and K is odd, negate the smallest positive number

  • Return the sum of the modified array

Example

Let's implement the solution ?

class Solution:
    def largestSumAfterKNegations(self, nums, k):
        # Sort array to handle negatives first
        nums.sort()
        
        # Negate negative numbers
        for i in range(len(nums)):
            if nums[i] < 0 and k > 0:
                nums[i] = -nums[i]
                k -= 1
            if k == 0:
                break
        
        # If k is odd, negate the smallest element
        if k % 2 == 1:
            smallest = min(nums)
            return sum(nums) - 2 * smallest
        else:
            return sum(nums)

# Test the solution
solution = Solution()
result = solution.largestSumAfterKNegations([3, -1, 0, 2], 3)
print(f"Maximum sum: {result}")
Maximum sum: 6

Step-by-Step Execution

Let's trace through the example with array [3, -1, 0, 2] and K = 3 ?

def trace_execution(nums, k):
    print(f"Initial array: {nums}, K = {k}")
    
    # Sort the array
    nums.sort()
    print(f"After sorting: {nums}")
    
    # Negate negative numbers
    original_k = k
    for i in range(len(nums)):
        if nums[i] < 0 and k > 0:
            print(f"Negating nums[{i}] = {nums[i]} to {-nums[i]}")
            nums[i] = -nums[i]
            k -= 1
            print(f"Array now: {nums}, remaining K = {k}")
        if k == 0:
            break
    
    print(f"After negating negatives: {nums}, remaining K = {k}")
    
    # Handle remaining operations
    if k % 2 == 1:
        smallest = min(nums)
        result = sum(nums) - 2 * smallest
        print(f"K is odd, smallest element: {smallest}")
        print(f"Final sum: {sum(nums)} - 2*{smallest} = {result}")
    else:
        result = sum(nums)
        print(f"K is even, final sum: {result}")
    
    return result

# Trace the execution
trace_execution([3, -1, 0, 2], 3)
Initial array: [3, -1, 0, 2], K = 3
After sorting: [-1, 0, 2, 3]
Negating nums[0] = -1 to 1
Array now: [1, 0, 2, 3], remaining K = 2
After negating negatives: [1, 0, 2, 3], remaining K = 2
K is even, final sum: 6

Alternative Approach Using Heap

We can also use a min-heap to always negate the smallest element ?

import heapq

def maximize_sum_heap(nums, k):
    # Convert to min-heap
    heapq.heapify(nums)
    
    # Always negate the smallest element
    for _ in range(k):
        smallest = heapq.heappop(nums)
        heapq.heappush(nums, -smallest)
    
    return sum(nums)

# Test with heap approach
result = maximize_sum_heap([3, -1, 0, 2], 3)
print(f"Result using heap: {result}")
Result using heap: 6

Comparison

Approach Time Complexity Space Complexity Best For
Sorting O(n log n) O(1) Simple implementation
Heap O(k log n) O(1) When K << n

Conclusion

The sorting approach efficiently maximizes the array sum by first negating negative numbers, then handling remaining operations optimally. The heap approach works better when K is much smaller than the array size.

Updated on: 2026-03-25T07:31:24+05:30

419 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements