本题简单一些,估计大家不用想着贪心 ,用自己直觉也会有思路。
Python:
- class Solution:
- def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:
- nums.sort(key=lambda x: abs(x), reverse=True) # 关键:按绝对值降序排列
- for i in range(len(nums)):
- if nums[i]<0 and k>0:
- nums[i] = -nums[i]
- k -= 1
- if k%2==1:
- nums[-1] *= -1
- return sum(nums)
C++:
- class Solution {
- static bool cmp(int a, int b) {
- return abs(a) > abs(b);
- }
- public:
- int largestSumAfterKNegations(vector<int>& nums, int k) {
- sort(nums.begin(), nums.end(), cmp); //注意:这里cmp是static method
- for (int i=0; i
size(); i++) { - if (nums[i]<0 && k>0) {
- nums[i] *= -1;
- k--;
- }
- }
- if (k%2==1) nums[nums.size()-1] *= -1;
- int ans = 0;
- for (int a:nums) ans+=a;
- return ans;
- }
- };
本题有点难度,不太好想,推荐大家熟悉一下方法二
Python:
情况三是比较难想到的,从后向前看如何覆盖cum_sum of net gas.
情况三:如果累加的最小值是负数,汽车就要从非0节点出发,从后向前,看哪个节点能把这个负数填平,能把这个负数填平的节点就是出发节点。
- class Solution:
- def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
- cum_sum = 0
- min_net = float('inf')
- for i in range(len(gas)):
- cum_sum += gas[i] - cost[i]
- if cum_sum < min_net:
- min_net = cum_sum
- if cum_sum < 0: return -1
- if min_net > 0: return 0
- for i in reversed(range(len(gas))):
- min_net += gas[i] - cost[i]
- if min_net >= 0:
- return i
- return -1
C++:
- class Solution {
- public:
- int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
- int cumSum = 0;
- int minCumSum = INT_MAX;
- for (int i=0; i
size(); i++) { - cumSum += gas[i] - cost[i];
- if (cumSum < minCumSum) minCumSum = cumSum;
- }
- if (cumSum < 0) return -1;
- if (minCumSum > 0) return 0;
- for (int i=gas.size()-1; i>=0; i--) {
- minCumSum += gas[i] - cost[i];
- if (minCumSum >=0) return i;
- }
- return -1;
- }
- };
本题涉及到一个思想,就是想处理好一边再处理另一边,不要两边想着一起兼顾,后面还会有题目用到这个思路
Python:
- class Solution:
- def candy(self, ratings: List[int]) -> int:
- n = len(ratings)
- if n == 1: return 1
- ans = [1] * n
- for i in range(1, n): # 从前往后
- if ratings[i] > ratings[i-1]:
- ans[i] = ans[i-1] + 1
- for i in reversed(range(n-1)): # 从后往前
- if ratings[i] > ratings[i+1]:
- ans[i] = max(ans[i], ans[i+1]+1)
- return sum(ans)
C++:
- class Solution {
- public:
- int candy(vector<int>& ratings) {
- if (ratings.size()==1) return 1;
- vector<int> candyVec(ratings.size(), 1);
- for (int i=1; i
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 ans = 0;
- for (int c: candyVec) ans += c;
- return ans;
- }
- };