classSolution { public: intmaxSubArray(vector<int>& nums){ int result = INT32_MIN; int count = 0; for (int i = 0; i < nums.size(); i ++) { count += nums[i]; if (count > result) { // 取区间累积的最大值 result = count; } if (count <= 0) count = 0; }
classSolution { public: intmaxProfit(vector<int>& prices){ int result = 0; for (int i = 1; i < prices.size(); i ++) { result += max(prices[i] - prices[i - 1], 0); }
classSolution { staticboolcmp(int a, int b){ returnabs(a) > abs(b); } public: intlargestSumAfterKNegations(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;
classSolution { public: intcanCompleteCircuit(vector<int>& gas, vector<int>& cost){ int curSum = 0; int min = INT_MAX; // 从起点出发,油箱里的油量最小值 for (int i = 0; i < gas.size(); i ++) { int rest = gas[i] - cost[i]; curSum += rest; if (curSum < min) { min = curSum; } } if (curSum < 0) // 情况1 return-1; if (min >= 0) // 情况2 return0; for (int i = gas.size() - 1; i >= 0; i --) { // 情况3 int rest = gas[i] - cost[i]; min += rest; if (min >= 0) { return i; } } return-1;
classSolution { public: intcandy(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];
classSolution { public: boollemonadeChange(vector<int>& bills){ int five = 0, ten = 0, twenty = 0; for (int bill : bills) { if (bill == 5) five ++; if (bill == 10) { if (five <= 0) returnfalse; ten ++; five --; } if (bill == 20) { if (five > 0 && ten > 0) { five --; ten --; twenty ++; } elseif (five >= 3) { five -= 3; twenty ++; } else { returnfalse; } } }
int result = 1; // need 1 arrow at least when ponints is empty for (int i = 1; i < points.size(); i ++) { if (points[i][0] > points[i-1][1]) { result ++; } else { // The two balloons are not close to each other points[i][1] = min(points[i-1][1], points[i][1]); } } return result; } };