1005. Maximize Sum Of Array After K Negations
Given an integer array nums and an integer k, modify the array in the following way:
- choose an index
iand replacenums[i]with-nums[i].
You should apply this process exactly k times. You may choose the same index i multiple times.
Return the largest possible sum of the array after modifying it in this way.
题目解析:
- 排序后将前k个负数转成正数
- 如果k比负数的数量大,则如果k为偶数则不变,如果k为奇数则将最小的正数或0转变符号
代码:
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
int sum = 0;
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
if (nums[i] < 0 && k > 0) {
nums[i] = -nums[i];
k--;
}
}
if (k > 0 && k % 2 != 0) {
Arrays.sort(nums);
nums[0] = -nums[0];
}
return Arrays.stream(nums).sum();
}
}
134. Gas Station
There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.
Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique
题目解析:
- 如果总油量减去总消耗大于等于零那么一定可以跑完一圈
- i从0开始累加rest[i],和记为curSum,一旦curSum小于零,说明[0, i]区间都不能作为起始位置,因为这个区间选择任何一个位置作为起点,到i这里都会断油,那么起始位置从i+1算起,再从0计算curSum。
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int totalSum = 0, curSum = 0;
int start = 0;
for (int i = 0; i < gas.length; i++) {
totalSum += gas[i] - cost[i];
curSum += gas[i] - cost[i];
if (curSum < 0) {
curSum = 0;
start = i + 1;
}
}
if (totalSum < 0) return -1;
return start;
}
}
135. Candy
There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.
You are giving candies to these children subjected to the following requirements:
- Each child must have at least one candy.
- Children with a higher rating get more candies than their neighbors.
Return the minimum number of candies you need to have to distribute the candies to the children.
题目解析:
- 糖果的数量由左右邻居共同决定,所以可以先满足一遍,再满足另一边
代码:
class Solution {
public int candy(int[] ratings) {
int[] candies = new int[ratings.length];
for (int i = 0; i < ratings.length; i++) {
if (i == 0) candies[i] = 1;
else {
if (ratings[i] > ratings[i-1]) {
candies[i] = candies[i-1] + 1;
} else {
candies[i] = 1;
}
}
}
int minSum = 0;
for (int i = ratings.length - 1; i >= 0; i--) {
if (i < ratings.length -1) {
if (ratings[i] > ratings[i+1]) {
candies[i] = Math.max(candies[i+1] + 1, candies[i]);
}
}
minSum += candies[i];
}
return minSum;
}
}