目录
Leecode 1005. Maximize Sum Of Array After K Negations
Leecode 1005. Maximize Sum Of Array After K Negations
题目地址:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
题目类型:贪心
思路:每次都选最小的变
class Solution {
public:
int largestSumAfterKNegations(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int>> qu;
for (auto& it : nums) qu.push(it);
while (k--) {
int tmp = qu.top();
tmp *= -1;
qu.pop();
qu.push(tmp);
}
int sum = 0;
while (qu.size()) {
sum += qu.top();
qu.pop();
}
return sum;
}
};
Leecode 134. Gas Station
题目地址:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
题目类型:贪心
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
// 维护一个前缀和数组,然后找到最低点,最低点的下一下就是起点
int mini, minnum = INT_MAX, presum = 0;
for (int i = 0; i < gas.size(); ++i) {
presum += gas[i] - cost[i];
if (presum < minnum) {
minnum = presum;
mini = i;
}
}
if (minnum > 0) return 0;
//
else if (presum < 0) return -1;
else return (mini + 1) % gas.size();
}
};
Leecode 135. Candy
题目地址:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
题目类型:贪心
思路:从左向右一次,从右向左一次
class Solution {
public:
int candy(vector<int>& ratings) {
// 每一个人都先分配一个
vector<int> nums(ratings.size(), 1);
// 从左向右
for (int i = 1; i < ratings.size(); ++i) {
if (ratings[i] > ratings[i - 1]) nums[i] = nums[i - 1] + 1;
}
for (int i = ratings.size() - 2; i >= 0; --i) {
if (ratings[i] > ratings[i + 1]) if (nums[i] <= nums[i + 1]) nums[i] = nums[i + 1] + 1;
}
return accumulate(nums.begin(), nums.end(), 0);
}
};