代码随想录算法训练营第三十五天
122.买卖股票的最佳时机II
题目链接:122.买卖股票的最佳时机II
class Solution {
public:
int maxProfit(vector<int>& prices) {
int sum = 0;
for (int i = 1; i < prices.size(); i++) {
int profit = prices[i] - prices[i - 1];//获取单日的最大利润,将所有正利润加和就是最大利润
if (profit > 0)
sum += profit;
}
return sum;
}
};
55. 跳跃游戏
题目链接:55. 跳跃游戏
class Solution {
public:
bool canJump(vector<int>& nums) {
int max_cover = 0;
for(int i = 0;i<nums.size();i++){
if(i>max_cover)return false;//如果当前位置已经超过最远能到达的位置了,证明跳跃以及结束了
int cover = nums[i]+i;//能跳的的最远距离是当前位置加上当前位置
max_cover =max(cover,max_cover);
if(max_cover>=nums.size()-1)return true;//到达的最远位置超过数组长度,证明可以跳到结尾
}
return false;
}
};
45.跳跃游戏II
题目链接:45.跳跃游戏II
class Solution {
public:
int jump(vector<int>& nums) {
int end =0;
int farthest =0;
int result = 0;
for(int i =0;i<nums.size();i++){
farthest = max(i+nums[i],farthest);//能到达的最远的下标
if(i==end){//已经跳到最远的下标了
end =farthest;//更新下一次能跳的最远坐标
result++;//跳跃次数+1
}
if(end>=nums.size()-1){break;}//跳跃的位置到最后一个下标,跳跃结束
}
return result;
}
};