-
1005.K次取反后最大化的数组和
-
class Solution { public: int largestSumAfterKNegations(vector<int>& nums, int k) { sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size(); i++) { if (nums[i] < 0 && k) { nums[i] = -nums[i]; k--; } } sort(nums.begin(), nums.end()); while (k != 0) { nums[0] = -nums[0]; k--; } int sum = 0; for (int i : nums) { sum += i; } return sum; } };
-
134. 加油站
-
class Solution { public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { int s = 0; int sum = 0; int sum1 = 0; for (int i = 0; i < gas.size() && s < gas.size(); i++) { sum1 += gas[i] - cost[i]; sum += gas[i] - cost[i]; if (sum < 0) { sum = 0; s = i + 1; } } if (sum1<0) return -1; return s; } };
-
135. 分发糖果
-
class Solution { public: int candy(vector<int>& ratings) { vector<int> a(ratings.size(), 1); int sum = 0; for (int i = 1; i < ratings.size(); i++) { if (ratings[i] > ratings[i - 1]) a[i]=a[i-1]+1; } for (int i = ratings.size() - 2; i >= 0; i--) { if (ratings[i] > ratings[i + 1]) a[i]=max(a[i],a[i+1]+1); } for (int i : a) sum += i; return sum; } };