122.买卖股票的最佳时机II
题目链接:. - 力扣(LeetCode)
文档讲解:代码随想录
视频讲解:贪心算法也能解决股票问题!LeetCode:122.买卖股票最佳时机II_哔哩哔哩_bilibili
状态:未通过
代码实现:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int result = 0;
for(int i = 1; i < prices.size(); i++){
result += max(prices[i] - prices[i - 1], 0);
}
return result;
}
};
55. 跳跃游戏
题目链接:. - 力扣(LeetCode)
文档讲解:代码随想录
视频讲解:贪心算法,怎么跳跃不重要,关键在覆盖范围 | LeetCode:55.跳跃游戏_哔哩哔哩_bilibili
状态:未通过
代码实现:
class Solution {
public:
bool canJump(vector<int>& nums) {
int cover = 0;
if(nums.size() == 1) return true;
for(int i = 0; i <= cover; i++){
cover = max(i + nums[i], cover);
if(cover >= nums.size() - 1) return true;
}
return false;
}
};
45.跳跃游戏II
题目链接:. - 力扣(LeetCode)
文档讲解:代码随想录
视频讲解:贪心算法,最少跳几步还得看覆盖范围 | LeetCode: 45.跳跃游戏II_哔哩哔哩_bilibili
状态:未通过
代码实现:
class Solution {
public:
int jump(vector<int>& nums) {
if(nums.size() == 1) return 0;
int curDistance = 0;
int nextDistance = 0;
int result = 0;
for(int i = 0; i < nums.size(); i++){
nextDistance = max(nums[i] + i, nextDistance);
if(i == curDistance){
result++;
curDistance = nextDistance;
if(nextDistance >= nums.size() - 1) break;
}
}
return result;
}
};