1005.K次取反后最大化的数组和
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
// 使用包装类型Integer的自定义比较器进行排序
Integer[] wrappedNums = new Integer[nums.length];
for (int i = 0; i < nums.length; i++) {
wrappedNums[i] = nums[i];
}
Arrays.sort(wrappedNums, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
// 比较两个数的绝对值,按照绝对值的大小降序排列
return Integer.compare(Math.abs(b), Math.abs(a));
}
});
for(int i = 0;i<wrappedNums.length;i++){
if(wrappedNums[i] < 0 && k > 0){
wrappedNums[i] = -wrappedNums[i];
k--;
}
}
if(k%2 == 1) wrappedNums[nums.length -1] = - wrappedNums[nums.length -1];
int sum = 0;
for (int num : wrappedNums) {
sum += num;
}
return sum;
}
}
- 加油站
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int curSum = 0;
int totalSum = 0;
int start = 0;
for(int i = start;i<gas.length;i++){
curSum += gas[i] - cost[i];
totalSum += gas[i] - cost[i];
if(curSum < 0){
start = i+1;
curSum = 0;
}
}
if(totalSum < 0) return -1;
return start;
}
}
- 分发糖果
class Solution {
public int candy(int[] ratings) {
int len = ratings.length;
int[] candyNum = new int[len];
candyNum[0] = 1;
//右边比左边大
for(int i = 1; i < ratings.length;i++){
candyNum[i] = (ratings[i] > ratings[i-1]) ? candyNum[i-1] + 1 : 1;
}
//左边比右边大
for(int i = ratings.length -2 ; i>=0;i--){
if(ratings[i] > ratings[i+1]){
candyNum[i] = Math.max(candyNum[i],candyNum[i+1]+1);
}
}
int sum = 0;
for(int num : candyNum){
sum += num;
}
return sum;
}
}