1005. K 次取反后最大化的数组和
class Solution {
static bool cmp(int a, int b) {
return abs(a) > abs(b);
}
public:
int largestSumAfterKNegations(vector<int>& nums, int k) {
sort(nums.begin(), nums.end(), cmp);
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] < 0 && k > 0) {
nums[i] = -nums[i];
k--;
}
}
if (k > 0) {
int len = nums.size();
int temp = k % 2;
if (temp == 1) {
nums[len - 1] = -nums[len - 1];
}
}
int result = 0;
for (int i = 0; i < nums.size(); ++i) {
result += nums[i];
}
return result;
}
};
134. 加油站
有些不是很明白题目的推导过程
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int curSum = 0;
int tolSum = 0;
int start = 0;
for (int i = 0; i < gas.size(); ++i) {
curSum += gas[i] - cost[i];
tolSum += gas[i] - cost[i];
if (curSum < 0) {
start = i + 1;
curSum = 0;
}
}
if (tolSum < 0) return -1;
return start;
}
};
135. 分发糖果
还是一样的,我们如何去理解这个推导过程?
class Solution {
public:
int candy(vector<int>& ratings) {
vector<int> candyNum(ratings.size(), 1);
for (int i = 1; i < ratings.size(); ++i) {
if (ratings[i] > ratings[i - 1]) {
candyNum[i] = candyNum[i - 1] + 1;
}
}
for (int j = ratings.size() - 1; j > 0; --j) {
if (ratings[j - 1] > ratings[j]) {
candyNum[j - 1] = max(candyNum[j - 1], candyNum[j] + 1);
}
}
int result = 0;
for (int i = 0; i < ratings.size(); ++i) {
result += candyNum[i];
}
return result;
}
};