- 1005.K次取反后最大化的数组和
按绝对值大小排序,Java要先装箱再排序(赶紧看看八股里面装箱开箱的内容)
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
Integer[] A = new Integer[nums.length];
for (int i = 0; i < nums.length; i++) {
A[i] = nums[i];
}
Arrays.sort(A, (a, b) -> {
return Math.abs(b) - Math.abs(a);
});
for (int i = 0; i < nums.length; i++) {
if (A[i] < 0 && k > 0) {
A[i] = -A[i];
k--;
}
}
if (k % 2 == 1) A[A.length - 1] *= -1;
int res = 0;
for (int a : A) res += a;
return res;
}
}
- 134. 加油站
不会
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int sum = 0;
int min = Integer.MAX_VALUE;
int minIndex = -1;
for(int i = 0; i < gas.length; i++){
sum = sum + gas[i] - cost[i];
if(sum < min && sum < 0){
min = sum;
minIndex = i;
}
}
if(sum < 0) return -1;
return (minIndex + 1 )%gas.length;
}
}
- 135. 分发糖果
class Solution {
public int candy(int[] ratings) {
int len = ratings.length;
int[] candy = new int[len];
candy[0] = 1;
for (int i = 1; i < len; i++) {
candy[i] = (ratings[i] > ratings[i - 1]) ? candy[i - 1] + 1 : 1;
}
for (int i = len - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) {
candy[i] = Math.max(candy[i], candy[i + 1] + 1);
}
}
int res = 0;
for (int n : candy) {
res += n;
}
return res;
}
}