122.买卖股票的最佳时机 II
这道题我愿称Carl哥为两行代码的神,这道题其实就是转化为求利润的最大,第N天的利润可以=n-(n-1)+(n-1)-(n-2)+...,就转化为了每两天之间的利润的和,所以只要计算每两天利润和的最大值就可以。
https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/
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. 跳跃游戏
我想说Carl哥我的神,我还在纠结它要怎么组合才能跳到最后,卡哥已经next level了,这道题其实就只是转换为覆盖范围而已,从第一个能跳的范围开始遍历,每次更新cover范围,所以遍历到达的地方越远,只要遍历得到就返回,巧妙之处在于把cover这个变化的量写入for循环里面。
https://leetcode.cn/problems/jump-game/
class Solution {
public:
bool canJump(vector<int>& nums) {
if(nums.size()==0)
{
return true;
}
int cover=0;
for(int i=0;i<=cover;i++)
{
cover=max(cover,i+nums[i]);
if(cover>=nums.size()-1)
return true;
}
return false;
}
};
45.跳跃游戏II
这道题区分于上一道题便是咱们不能直接把cover放在for循环里了,上一题是不断地开拓领土,但这道题在于咱们还要知道步数,所以这一道题的思路是先在现有的cover范围内遍历,假如说已经走到现有cover的最后一位了,咱们就检查这个cover内所产生的下一个覆盖范围nextcover是否能够覆盖到数组的最后一位,假如能,咱们就返回,如果不能,再在下一个覆盖范围nextcover里面遍历,注意,咱们是先走着,再记录步数ans。
https://leetcode.cn/problems/jump-game/
class Solution {
public:
bool canJump(vector<int>& nums) {
if(nums.size()==0)
{
return true;
}
int cover=0;
for(int i=0;i<=cover;i++)
{
cover=max(cover,i+nums[i]);
if(cover>=nums.size()-1)
return true;
}
return false;
}
};