目录
LeetCode 122.买卖股票的最佳时机II
文章讲解:代码随想录
代码如下(Java):
class Solution {
public int maxProfit(int[] prices) {
int result = 0;
for(int i = 1; i < prices.length; i++){
result += Math.max(prices[i] - prices[i-1],0);
}
return result;
}
}
LeetCode 55. 跳跃游戏
文章讲解:代码随想录
视频讲解:贪心算法,怎么跳跃不重要,关键在覆盖范围 | LeetCode:55.跳跃游戏_哔哩哔哩_bilibili
力扣题目:LeetCode 55. 跳跃游戏
代码如下(Java):
class Solution {
public boolean canJump(int[] nums) {
if(nums.length == 1) return true;
int cover = 0;
for(int i = 0; i <= cover; i++){
cover = Math.max(i + nums[i], cover);
if(cover >= nums.length - 1){
return true;
}
}
return false;
}
}
LeetCode 45.跳跃游戏II
文章讲解:代码随想录
视频讲解:贪心算法,最少跳几步还得看覆盖范围 | LeetCode: 45.跳跃游戏II_哔哩哔哩_bilibili
力扣题目: LeetCode 45.跳跃游戏II

代码如下(Java):
class Solution {
public int jump(int[] nums) {
if(nums == null || nums.length == 0 || nums.length == 1) return 0;
int count = 0;
int curDistance = 0;
int maxDistance = 0;
for(int i = 0; i < nums.length; i++){
maxDistance = Math.max(maxDistance, i + nums[i]);
if(maxDistance >= nums.length - 1){
count++;
break;
}
if(i == curDistance){
curDistance = maxDistance;
count++;
}
}
return count;
}
}
本文介绍了如何使用贪心算法解决LeetCode中的两个问题:122.买卖股票的最佳时机II和55/45.跳跃游戏系列。通过Java代码示例,展示了如何在股票交易中找到最大利润和判断最少跳跃次数来覆盖数组。

被折叠的 条评论
为什么被折叠?



