力扣122.买卖股票的最佳时机2
题目链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/
思路
将整体收益拆分为每日收益。
例如,第0天到第3天的收益是prices[3]-prices[0]。可以拆分为(prices[3]-prices[2])+(prices[2]-prices[1])+(prices[1]-prices[0])。
所以说,只要求得每日收益,再只统计正数的收益。要注意,第0天是没有收益的,第1天才有收益。
完整代码
class Solution {
public int maxProfit(int[] prices) {
int res = 0;
int num = 0;
for (int i = 1; i < prices.length; i++) {
num = prices[i] - prices[i-1];
if(num > 0){
res += num;
}
}
return res;
}
}
力扣55.跳跃游戏
题目链接:https://leetcode.cn/problems/jump-game/
思路
不用管一次跳一步还是几步,只要当前索引能跳的步数能覆盖到最后一个索引就是能跳到。
所以问题就转换为了当前能跳的最大范围。
cover表示以当前索引为起点,能跳到的最远距离。使i在cover范围里移动,i每移动一下,更新cover值,如果最后cover能覆盖到最后一个索引,返回true。
完整代码
class Solution {
public boolean canJump(int[] nums) {
int cover = 0;
if(nums.length == 1) return true;
for (int i = 0; i <= cover; i++) {
cover = Math.max(cover,nums[i]+i);
if(cover >= nums.length - 1){
return true;
}
}
return false;
}
}
力扣45.跳跃游戏2
题目链接:https://leetcode.cn/problems/jump-game-ii/
思路
就是移动下标达到了当前覆盖的最远距离下标时,步数就要加一,来增加覆盖距离。
最后的步数就是最少步数。
特殊情况:
1.如果当前覆盖最远距离下标不是集合终点,步数就加一,还需要继续走。
2.如果当前覆盖最远距离下标就是集合终点,步数不用加一,因为不能再往后走了。
完整代码
class Solution {
public int jump(int[] nums) {
int count = 0;//要走的步数
int curdistance = 0;//当前能覆盖的最大范围
int nextdistance = 0;//下一步能覆盖的最大范围
for (int i = 0; i < nums.length; i++) {
nextdistance = Math.max(nums[i]+i,nextdistance);//更新下一步能覆盖的最大范围
if(i == curdistance){//遇到当前最远覆盖下标
if(curdistance != nums.length-1){//当前最远覆盖下标不是终点
count++;//步数必须加1
curdistance = nextdistance;//更新当前最远覆盖范围
}else break;//当前最远覆盖下标已经是终点,步数不需要再加
}
}
return count;
}
}