文档链接:https://programmercarl.com/
LeetCode122.买卖股票的最佳时机Ⅱ
题目链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/
思路:一次AC!!!贪心,秒了!
贪心:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int result = 0;
for(int i = 0; i < prices.size() - 1; i++) {
if(prices[i] < prices[i + 1]) {
result += prices[i + 1] - prices[i];
}
}
return result;
}
};
LeetCode55.跳跃游戏
题目链接:https://leetcode.cn/problems/jump-game/
思路:覆盖的想法太巧妙了!
贪心:
class Solution {
public:
bool canJump(vector<int>& nums) {
int cover = 0;
for(int i = 0; i <= cover; i++) {
cover = max(cover, i + nums[i]);
if(cover >= nums.size() - 1) return true;
}
return false;
}
};
LeetCode45.跳跃游戏Ⅱ
题目链接:https://leetcode.cn/problems/jump-game-ii/
思路:关键在于当前覆盖范围内的最大步数,以及何时更新下一步
贪心:
class Solution {
public:
int jump(vector<int>& nums) {
int cur = 0;
int next = 0;
int result = 0;
for(int i = 0; i < nums.size(); i++) {
next = max(next, i + nums[i]);
if(i == cur) {
if(cur != nums.size() - 1) {
result++;
cur = next;
} else break;
}
}
return result;
}
};
总结:贪心还是好难,没有套路可言。