Open youngyangyang04 opened 6 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;
}
}
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
Arrays.sort(nums);
int minNum=Integer.MAX_VALUE;
int ans=0;
for(int num:nums){
if(num<0&&k>0){
ans-=num;
k--;
minNum=Math.min(minNum,-num);
}
else {
ans+=num;
minNum=Math.min(minNum,num);
}
}
return k%2==0? ans:ans-2*minNum;
}
}
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