自定义根据绝对值排序
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
List<Integer> arr = new ArrayList<>();
for(int num:nums){
arr.add(num);
}
Collections.sort(arr, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return Math.abs(o2)-Math.abs(o1);
}
});
for (int i = 0;i< arr.size();i++){
if(arr.get(i)<0&&k>0){
arr.set(i,-arr.get(i));
k--;
}
}
int len = arr.size();
if(k%2==1)arr.set(len-1,-arr.get(len-1));
int ans = 0;
for (int i = 0;i<arr.size();i++){
ans+=arr.get(i);
}
return ans;
}
}