【代码随想录】29

8


2023年10月11日 - 贪心算法3

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

 class Solution {
 static bool cmp(int a, int b) {
     return abs(a) > abs(b);
 }
 public:
     int largestSumAfterKNegations(vector<int>& A, int K) {
         sort(A.begin(), A.end(), cmp);       // 第一步
         for (int i = 0; i < A.size(); i++) { // 第二步
             if (A[i] < 0 && K > 0) {
                 A[i] *= -1;
                 K--;
             }
         }
         if (K % 2 == 1) A[A.size() - 1] *= -1; // 第三步
         int result = 0;
         for (int a : A) result += a;        // 第四步
         return result;
     }
 };

134. 加油站

 class Solution {
 public:
     int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
         int curSum = 0;
         int totalSum = 0;
         int start = 0;
         for (int i = 0; i < gas.size(); i++) {
             curSum += gas[i] - cost[i];
             totalSum += gas[i] - cost[i];
             if (curSum < 0) {   // 当前累加rest[i]和 curSum一旦小于0
                 start = i + 1;  // 起始位置更新为i+1
                 curSum = 0;     // curSum从0开始
             }
         }
         if (totalSum < 0) return -1; // 说明怎么走都不可能跑一圈了
         return start;
     }
 };

135. 分发糖果

向左对比就要向右遍历,向右对比就要向左遍历

 class Solution {
 public:
     int candy(vector<int>& ratings) {
         vector<int> candyVec(ratings.size(), 1);
         // 从前向后
         for (int i = 1; i < ratings.size(); i++) {
             if (ratings[i] > ratings[i - 1]) candyVec[i] = candyVec[i - 1] + 1;
         }
         // 从后向前
         for (int i = ratings.size() - 2; i >= 0; i--) {
             if (ratings[i] > ratings[i + 1] ) {
                 candyVec[i] = max(candyVec[i], candyVec[i + 1] + 1);
             }
         }
         // 统计结果
         int result = 0;
         for (int i = 0; i < candyVec.size(); i++) result += candyVec[i];
         return result;
     }
 };