Day 33
1005. K 次取反后最大化的数组和
class Solution {
public:
int largestSumAfterKNegations(vector<int>& nums, int k) {
unordered_map<int, int> freq;
for (int num: nums) {
freq[num] += 1;
}
int ans = accumulate(nums.begin(), nums.end(), 0);
for (int i = -100; i < 0; ++i) {
if (freq[i]) {
int ops = min(k, freq[i]);
ans += (-i) * ops * 2;
freq[i] -= ops;
freq[-i] += ops;
k -= ops;
if (k == 0) {
break;
}
}
}
if (k > 0 && k % 2 == 1 && !freq[0]) {
for (int i = 1; i <= 100; ++i) {
if (freq[i]) {
ans -= i * 2;
break;
}
}
}
return ans;
}
};
134. 加油站
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int n = gas.size();
int i = 0;
while (i < n) {
int sumOfGas = 0, sumOfCost = 0;
int cnt = 0;
while (cnt < n) {
int j = (i + cnt) % n;
sumOfGas += gas[j];
sumOfCost += cost[j];
if (sumOfCost > sumOfGas) {
break;
}
cnt++;
}
if (cnt == n) {
return i;
} else {
i = i + cnt + 1;
}
}
return -1;
}
};
135. 分发糖果
class Solution {
public:
int candy(vector<int>& ratings) {
int l = ratings.size();
vector<int> leftR(l,1);
vector<int> rightR(l,1);
int sum = 0;
for(int i = 1; i < l; i++) {
if(ratings[i] > ratings[i - 1]) {
leftR[i] = leftR[i - 1] + 1;
}
}
for(int i = l - 2; i >= 0; i--) {
if(ratings[i] > ratings[i+1]) {
rightR[i] = rightR[i+1] + 1;
}
}
for(int i = 0; i < l; i++) {
sum += max(leftR[i], rightR[i]);
}
return sum;
}
};