day29:贪心part3
1005.K 次取反后最大化的数组和
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
nums = IntStream.of(nums)
.boxed()
.sorted((a, b) -> Math.abs(a) - Math.abs(b))
.mapToInt(Integer::intValue).toArray();
for (int i = nums.length - 1; i >= 0; i--) {
if (nums[i] < 0 && k > 0) {
nums[i] = -nums[i];
k--;
}
}
if (k % 2 == 1) nums[0] = -nums[0];
return Arrays.stream(nums).sum();
}
}
134.加油站
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int curSum = 0;
int totalSum = 0;
int start = 0;
for (int i = 0; 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;
else return start;
}
}
135.分发糖果
class Solution {
public int candy(int[] ratings) {
int[] candy = new int[ratings.length];
candy[0] = 1;
for (int i = 1; i < ratings.length; i++) {
if (ratings[i] > ratings[i - 1])
candy[i] = candy[i - 1] + 1;
else candy[i] = 1;
}
for (int i = ratings.length - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1])
candy[i] = Math.max(candy[i], candy[i + 1] + 1);
}
return Arrays.stream(candy).sum();
}
}