代码随想录训练营 Day32
今日任务
122.买卖股票的最佳时机Ⅱ
55.跳跃游戏
45.跳跃游戏Ⅱ
语言:Java
122. 买卖股票的最佳时机Ⅱ
链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/
思路参考摆动序列
class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
int preDiff = 0;
int curDiff = 0;
for(int i = 1; i < prices.length; i++){
curDiff = prices[i] - prices[i - 1];
if(preDiff <= 0 && curDiff > 0){
profit += curDiff;
}
}
return profit;
}
}
55. 跳跃游戏
链接:https://leetcode.cn/problems/jump-game/
class Solution {
public boolean canJump(int[] nums) {
if(nums.length == 1){
return true;
}
int cover = 0;
//for(int i = 0; i < nums.length; i++){
for(int i = 0; i <= cover; i++){ //每次只在cover的范围内移动,看最后能移动到哪里去
//cover += nums[i];
cover = Math.max(i + nums[i], cover);
if(cover >= nums.length - 1){
return true;
}
}
return false; //说明直到i走到最大覆盖范围都没有到达最后位置
}
}
45. 跳跃游戏Ⅱ
链接:https://leetcode.cn/problems/jump-game-ii/
思路:先得到本次的最远距离,在到达本次最远距离前,一边跳一边计算下次跳跃的最远距离,每次都是先跳到本次的最远距离再进行下一次操作。
class Solution {
public int jump(int[] nums) {
if(nums.length == 1){
return 0;
}
int step = 0;
int curDistance = 0;
int nextDistance = 0;
for(int i = 0; i < nums.length; i++){
nextDistance = Math.max(i + nums[i], nextDistance);
if(i == curDistance){
if(i != nums.length - 1){
step++;
curDistance = nextDistance;
if(nextDistance >= nums.length - 1){
break;
}
}
else{
break;
}
}
}
return step;
}
}
因为这道题说了保证一定会到达最后一个位置,所以不需要再考虑中间有0没办法到最后一个位置怎么办。
如果curDistance的位置正好在倒数第二个位置,那么再跳一次是肯定能到的(题目保证一定能跳到最后位置,所以nextDistance一定会覆盖最后的位置);如果curDistance不在倒数第二个位置,那就是普通的情形,一次次继续跳即可;这种解法就是将最后位置这个特殊情形和普通情形统一在了一起。
class Solution {
public int jump(int[] nums) {
if(nums.length == 1){
return 0;
}
int step = 0;
int curDistance = 0;
int nextDistance = 0;
for(int i = 0; i < nums.length - 1; i++){
nextDistance = Math.max(i + nums[i], nextDistance);
if(i == curDistance){
step++;
curDistance = nextDistance;
}
}
return step;
}
}