Given an array
A
of integers, we must modify the array in the following way: we choose ani
and replaceA[i]
with-A[i]
, and we repeat this processK
times in total. (We may choose the same indexi
multiple times.)Return the largest possible sum of the array after modifying it in this way.
Example 1:
Input: A = [4,2,3], K = 1 Output: 5 Explanation: Choose indices (1,) and A becomes [4,-2,3].Example 2:
Input: A = [3,-1,0,2], K = 3 Output: 6 Explanation: Choose indices (1, 2, 2) and A becomes [3,1,0,2].Example 3:
Input: A = [2,-3,-1,5,-4], K = 2 Output: 13 Explanation: Choose indices (1, 4) and A becomes [2,3,-1,5,4].
Note:
1 <= A.length <= 10000
1 <= K <= 10000
-100 <= A[i] <= 100
垃圾代码,待重构
public int largestSumAfterKNegations(int[] A, int K) {
Arrays.sort(A);
if (A[0] > 0) return posArray(A, K);
if (A[A.length - 1] < 0) return negArray(A, K);
else return mixArray(A, K);
}
private int mixArray(int[] arr, int K) {
int p=0;
while (arr[p] < 0) p++;
int sum = 0;
if (K <= p) {
for (int i = 0; i < arr.length; i++) {
if (i < K) arr[i] = -arr[i];
sum += arr[i];
}
} else
if ((K - p) % 2 == 1) {
for (int i = 0; i < arr.length; i++) {
sum += Math.abs(arr[i]);
}
if (Math.abs(arr[p-1]) > Math.abs(arr[p])) {
sum -= 2*Math.abs(arr[p]);
} else {
sum -= 2*Math.abs(arr[p-1]);
}
} else {
for (int i : arr) {
sum += Math.abs(i);
}
}
return sum;
}
private int posArray(int[] arr, int K) {
if (K % 2 == 1) arr[0] = -arr[0];
int sum = 0;
for (int it : arr) {
sum += it;
}
return sum;
}
private int negArray(int[] arr, int K) {
int sum = 0;
if (K <= arr.length) {
for (int i = 0; i < arr.length; i++) {
if (i < K) sum += -arr[i];
else sum += arr[i];
}
} else if (K > arr.length && (K - arr.length) % 2 == 1) {
for (int i = 0; i < arr.length; i++) {
sum += Math.abs(arr[i]);
}
sum += arr[arr.length-1];
}
return sum;
}