Open youngyangyang04 opened 3 months ago
class Solution {
public int largestSumAfterKNegations(int[] A, int K) {
List<Integer> B = new ArrayList<>();
for (int x : A) B.add(x);
Collections.sort(B, (a, b) -> Integer.compare(Math.abs(b), Math.abs(a)));
for (int i = 0; i < B.size(); i++) {
if (B.get(i) < 0 && K > 0) {
B.set(i, -B.get(i));
K--;
}
}
for(int i = 0; i < K; i++){
B.set(B.size() - 1, -B.getLast());
}
int sum = 0;
for (int x : B) sum += x;
return sum;
}
}
https://www.programmercarl.com/1005.K%E6%AC%A1%E5%8F%96%E5%8F%8D%E5%90%8E%E6%9C%80%E5%A4%A7%E5%8C%96%E7%9A%84%E6%95%B0%E7%BB%84%E5%92%8C.html