1005. K 次取反后最大化的数组和

按照绝对值大小排序,然后反转绝对值最大的复数并且k--,如果都大于0了并且k还是奇数,就把绝对值最小的反转,最后求和

 1 class Solution {
 2 public:
 3     static bool compare(int a, int b){
 4         return abs(a) > abs(b);
 5     }
 6     int largestSumAfterKNegations(vector<int>& nums, int k) {
 7         sort(nums.begin(),nums.end(), compare);
 8         for(int i = 0; i < nums.size(); i++){
 9             if(nums[i] < 0 && k > 0){
10                 nums[i] = -nums[i];
11                 k--;
12             }
13         }
14         if(k % 2)   nums[nums.size() - 1] = -nums[nums.size()-1];
15         int result = 0;
16         for(int num : nums){
17             result += num;
18         }
19         return result;
20     }
21 };

134. 加油站

 1 class Solution {
 2 public:
 3     int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
 4         int n = gas.size();
 5         // 当前剩余汽油
 6         int curSum = 0;
 7         // 所有的剩余汽油
 8         int totalSum = 0;
 9         // 起始位置
10         int result = 0;
11         for(int i = 0; i < n; i++){
12             curSum += gas[i] - cost[i];
13             totalSum += curSum;
14             if(curSum < 0){
15                 result = i + 1;
16                 curSum = 0;
17             }
18         }
19         if(totalSum < 0)    return -1;
20         return result;
21     }
22 };

135. 分发糖果

正着遍历一遍,然后倒着遍历一遍

 1 class Solution {
 2 public:
 3     int candy(vector<int>& ratings) {
 4         int result = 0;
 5         vector<int> vec(ratings.size(),1);
 6         for(int i = 1; i < vec.size(); i++){
 7             if(ratings[i] > ratings[i-1])
 8                 vec[i] = vec[i-1]+1;
 9         }
10 
11         for(int i = vec.size()-2; i >= 0; i--){
12             if(ratings[i] > ratings[i+1])
13                 vec[i] = max(vec[i+1] + 1,vec[i]);
14         }
15 
16         for(int v : vec){
17             result += v;
18         }
19         return result;
20     }
21 };