The problem “1005. Maximize Sum Of Array After K Negations” on LeetCode can be described as follows:
Given an array of integers nums
and an integer k
, you should perform k
negations on the elements of the array such that the sum of the array is maximized. Each negation flips the sign of an element from positive to negative or from negative to positive. Return the maximum possible sum of the array after k
negations.
Example:
Input: nums = [4,2,3], k = 1
Output: 5
Explanation: Choose index 1 and nums becomes [4,-2,3].
nums
and the value of k
?
nums
can range from -10^4
to 10^4
and k
can range from 0
to 10^4
.Here is the step-by-step strategy to solve this problem:
k
flips.k
is even, flipping any number twice ends up with no change in value. Therefore, the sum remains the same.k
is odd, flip the smallest value (positive or negative) to minimize the sum reduction.def largestSumAfterKNegations(nums, k):
# Sort the array to handle the smallest (most negative) values first
nums.sort()
# Flip the sign of negative numbers, if possible
for i in range(len(nums)):
if nums[i] < 0 and k > 0:
nums[i] = -nums[i]
k -= 1
# If there are flips remaining (k might be even or odd)
if k > 0:
# If k is odd, we need to flip the smallest element one more time
# Sort again to find the smallest element
nums.sort()
if k % 2 == 1:
nums[0] = -nums[0]
# Compute and return the sum of the array
return sum(nums)
# Example usage:
nums = [4, 2, 3]
k = 1
print(largestSumAfterKNegations(nums, k)) # Output: 5
Thus, the overall time complexity is (O(n \log n)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?