#1005

Maximize Sum Of Array After K Negations

Easy
ArrayGreedySortingGreedySorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal approach focuses on negating the smallest elements first to maximize the overall sum. By sorting the array, we can efficiently determine which elements to negate.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the array in ascending order.
  2. 2Step 2: Negate the smallest k elements (or fewer if there are not enough negative elements).
  3. 3Step 3: If k is still odd after negating, negate the smallest absolute value element.
  4. 4Step 4: Calculate the sum of the modified array.
solution.py10 lines
1# Full working Python code
2
3def maxSumAfterKNegations(nums, k):
4    nums.sort()
5    for i in range(min(k, len(nums))):
6        nums[i] = -nums[i]
7    if (k - len(nums)) % 2 == 1:
8        nums.sort()
9        nums[0] = -nums[0]
10    return sum(nums)

Complexity note: The complexity is dominated by the sorting step, which is O(n log n). The subsequent operations are linear.

  • 1Negating the smallest elements first maximizes the sum.
  • 2If k is odd after negating, we need to negate the smallest absolute value element.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.