Leetcode 1005. Maximize Sum Of Array After K Negations
Given an array A
of integers, we must perform K
operations. In each operation, we can choose an element of the array and change its sign (i.e., we can negate its value). Our goal is to maximize the sum of the array after exactly K
operations.
1 <= A.length <= 10^4
, -10^100 <= A[i] <= 10^100
, 1 <= K <= 10^4
.K
negations.K
operations or until you run out of negative numbers.import java.util.Arrays;
public class MaximizeSumAfterKNegations {
public int largestSumAfterKNegations(int[] nums, int k) {
// Step 1: Sort the array
Arrays.sort(nums);
// Step 2: Negate the smallest (most negative) elements
for (int i = 0; i < nums.length && k > 0; i++) {
if (nums[i] < 0) {
nums[i] = -nums[i];
k--;
}
}
// Step 3: Sort the array again to find the smallest absolute value
Arrays.sort(nums);
// Step 4: If k is odd, negate the smallest absolute value element
if (k % 2 != 0) {
nums[0] = -nums[0];
}
// Step 5: Sum up the array
int sum = 0;
for (int num : nums) {
sum += num;
}
return sum;
}
public static void main(String[] args) {
MaximizeSumAfterKNegations solution = new MaximizeSumAfterKNegations();
int[] nums = {3, -1, 0, 2};
int k = 3;
System.out.println(solution.largestSumAfterKNegations(nums, k)); // Output: 6
}
}
O(n log n)
where n
is the length of the array.K
elements: O(K)
which is effectively O(n)
in the worst case if K >= n
.O(n log n)
.O(n)
.Overall, the time complexity is dominated by the sorting steps, making it 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?