Given an array A of integers, we must modify the array in the following way: we choose an i and replace A[i] with -A[i], and we repeat this process K times in total. (We may choose the same index i 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
解題思路
要讓總和最大,需要每次都取反最小的元素。一個優(yōu)化點是:如果最小的元素是正數(shù),可以直接得到最終結(jié)果,無需每次都遍歷找到最小元素(最小正數(shù)取反之后還是最小的)。
實現(xiàn)代碼
實現(xiàn)1:
//Runtime: 2 ms, faster than 92.17% of Java online submissions for Maximize Sum Of Array After K Negations.
//Memory Usage: 38 MB, less than 100.00% of Java online submissions for Maximize Sum Of Array After K Negations.
class Solution {
public int largestSumAfterKNegations(int[] A, int K) {
int sum = getSum(A);
while (K-- > 0) {
int index = getIndexOfSmallest(A);
A[index] = -A[index];
sum += 2 * A[index];
}
return sum;
}
public int getSum(int[] nums) {
int result = 0;
for (int num : nums) {
result += num;
}
return result;
}
public int getIndexOfSmallest(int[] nums) {
int smallest = Integer.MAX_VALUE;
int index = -1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] < smallest) {
smallest = nums[i];
index = i;
}
}
return index;
}
}
實現(xiàn)2:
//Runtime: 1 ms, faster than 99.93% of Java online submissions for Maximize Sum Of Array After K Negations.
//Memory Usage: 38 MB, less than 100.00% of Java online submissions for Maximize Sum Of Array After K Negations.
class Solution {
public int largestSumAfterKNegations(int[] A, int K) {
int sum = getSum(A);
while (K > 0) {
int index = getIndexOfSmallest(A);
if (A[index] < 0) {
K--;
A[index] = -A[index];
sum += 2 * A[index];
} else {
if (K % 2 == 0) {
return sum;
} else {
return sum - 2 * A[index];
}
}
}
return sum;
}
public int getSum(int[] nums) {
int result = 0;
for (int num : nums) {
result += num;
}
return result;
}
public int getIndexOfSmallest(int[] nums) {
int smallest = Integer.MAX_VALUE;
int index = -1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] < smallest) {
smallest = nums[i];
index = i;
}
}
return index;
}
}