训练营打卡Day32
文章目录
题79:122. 买卖股票的最佳时机 II
思路
- 定义一个变量result来存储最大收益,初始值为0。
- 使用一个循环遍历所有的股票价格,从第二天开始遍历(因为不可能在第一天就卖出股票)。
- 对于每一天,计算当天卖出股票所能获得的收益。收益等于当天卖出股票的价格减去前一天买入的价格。
- 如果收益大于0,就将result加上收益;否则,result不变。
- 最后,返回result
代码
class Solution {
public:
int maxProfit(vector<int>& prices) {
int result = 0;
for(int i = 1; i < prices.size(); i++)
{
int profit = max(0, prices[i] - prices[i-1]);
result += profit;
}
return result;
}
};
题80:55. 跳跃游戏
思路
-
定义一个变量cover来存储能跳到的最远位置,初始值为0。
-
使用一个循环遍历所有的位置,从第一个位置开始遍历。
-
对于每一个位置,更新cover。新的cover是当前位置加上当前位置的跳力和原来的cover的最大值。
-
如果新的cover大于等于数组的长度减一,就说明能够跳到最后一个位置,返回true。
-
如果循环结束,返回false。
代码
class Solution {
public:
bool canJump(vector<int>& nums) {
int cover = 0;
for(int i = 0; i<= cover; i++)
{
cover = max(i + nums[i], cover);
if(cover >= nums.size()-1) return true;
}
return false;
}
};
题81:45. 跳跃游戏 II
思路
- 定义三个变量:curDistance表示当前能跳到的最远位置,ans表示跳到最后一个位置所需的最少步数,nextDistance表示下一步能跳到的最远位置,初始值分别为0、0和0。
- 使用一个循环遍历所有的位置,从第一个位置开始遍历,循环条件是当前位置小于数组的长度减一(因为最后一个位置不用跳)。
- 对于每一个位置,更新nextDistance。新的nextDistance是当前位置加上当前位置的跳力和原来的nextDistance的最大值。
- 如果当前位置等于curDistance,就说明已经跳到了能跳到的最远位置,需要再次跳跃。此时,将curDistance更新为nextDistance,并将ans加一。
- 最后,返回ans。
代码
class Solution {
public:
int jump(vector<int>& nums) {
int curDistance = 0;
int ans = 0;
int nextDistance = 0;
for(int i = 0; i < nums.size() - 1 ; i++)
{
nextDistance = max(nums[i]+i, nextDistance);
if(i == curDistance)
{
curDistance = nextDistance;
ans++;
}
}
return ans;
}
};