文章链接:代码随想录
题目链接:1005.K次取反后最大化的数组和
class Solution {
public:
static bool cmp(int a, int b){
return abs(a) > abs(b);
}
int largestSumAfterKNegations(vector<int>& nums, int k) {
int res = 0;
sort(nums.begin(), nums.end(), cmp);
for (int i = 0; i < nums.size(); i++){
if (nums[i] < 0 && k > 0){
nums[i] *= -1;
k--;
}
}
if (k > 0 && k % 2 == 1) nums[nums.size() - 1] *= -1;
for (int i : nums) res += i;
return res;
}
};
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int sum = 0;
int min = INT_MAX;
int rest = 0;
for (int i = 0; i < gas.size(); i++){
rest += gas[i] - cost[i];
if (rest < min){
min = rest;
}
}
if (rest < 0) return -1;
if (min >= 0) return 0;
for (int i = gas.size() - 1; i > 0; i--){
min += gas[i] - cost[i];
if (min >= 0) return i;
}
return false;
}
};
class Solution {
public:
int candy(vector<int>& ratings) {
vector<int> res(ratings.size(), 1);
for (int i = 1; i < ratings.size(); i++){
if (ratings[i] > ratings[i - 1]) res[i] = res[i - 1] + 1;
}
for (int i = ratings.size() - 2; i >= 0; i--){
if (ratings[i] > ratings[i + 1]) {
res[i] = max(res[i], res[i + 1] + 1);
}
}
int result = 0;
for (int i : res){
result += i;
}
return result;
}
};
第三十三天休息,三十四天打卡。加油!!!