代码随想录二刷Day32
今日任务
122.买卖股票的最佳时机II
55.跳跃游戏
45.跳跃游戏II
语言:C++
122. 买卖股票的最佳时机II
链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/
class Solution {
public:
int maxProfit(vector<int>& prices) {
int profit = 0;
int buy = prices[0], sell = 0;
for(int i = 1; i < prices.size(); i++){
sell = prices[i];
if(sell > buy) profit += sell - buy;
buy = prices[i];
}
return profit;
}
};
55. 跳跃游戏
链接:https://leetcode.cn/problems/jump-game/
class Solution {
public:
bool canJump(vector<int>& nums) {
int maxPos = 0;
for(int i = 0; i <= maxPos; i++){
maxPos = max(maxPos, i + nums[i]);
if(maxPos >= nums.size() - 1) return true;
}
return false;
}
};
45. 跳跃游戏II
链接:https://leetcode.cn/problems/jump-game-ii/
这个方法的巧妙之处在于循环终止条件的判断,因为题目保证一定会到达n-1的位置,所以我们只要保证能跳到n-2的位置即可。
可能会想问如果从n-1到n-2如果还需要跳一步的话该怎么办呢?假如此时 i 和 curPos 都是n-2,那么会进入if条件判断,res会再加1,得到正确的结果。
class Solution {
public:
int jump(vector<int>& nums) {
int curPos = 0;
int nextPos = 0;
int res = 0;
for(int i = 0; i < nums.size() - 1; i++){
nextPos = max(nextPos, i + nums[i]);
if(i == curPos){
curPos = nextPos;
res++;
}
}
return res;
}
};