赞
踩
先处理负数,在处理最小的数。
- class Solution {
- public:
- int largestSumAfterKNegations(vector<int>& nums, int k) {
- sort(nums.begin(), nums.end());
- int result = 0;
- for (int i = 0; i < nums.size(); i++) {
- if (nums[i] < 0 && k > 0) {
- nums[i] = -nums[i];
- k--;
- }
- result += nums[i];
- }
- sort(nums.begin(), nums.end());
- result -= nums[0] * (k % 2 == 0 ? 0 : 2);
- return result;
- }
- };
total_sum记录能否走到终点,cur_sum为判断起始点位置为小于0的后一个点。
- class Solution {
- public:
- int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
- int size = gas.size();
- int total_sum = 0, cur_sum = 0;
- int Index = 0;
- for (int i = 0; i < size; i++) {
- cur_sum += gas[i] - cost[i];
- total_sum += gas[i] - cost[i];
- if (cur_sum < 0) {
- cur_sum = 0;
- Index = i+1;
- }
- }
- if (total_sum < 0)
- return -1;
- return Index;
- }
- };
左右两边分别计算应该满足的糖果数量。先从左往右,如果比前面的大,就加一,否则则置一。
从右往左,如果比前面的大,就加一,否则取和原来相比的最大的。
- class Solution {
- public:
- int candy(vector<int>& ratings) {
- int size = ratings.size();
- vector<int> candy(size, 1);
- for (int i = 1; i < size; i++) {
- if (ratings[i - 1] < ratings[i]) {
- candy[i] = candy[i - 1] + 1;
- }
-
- }
- for (int i = size - 2; i >= 0; i--) {
- if (ratings[i] > ratings[i + 1]) {
- candy[i] = max(candy[i], candy[i + 1] + 1);
- }
- }
- int result = 0;
- for (int i = 0; i < size; i++)
- result += candy[i];
- return result;
- }
- };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。