122.买卖股票的最佳时机II
cpp
class Solution {
public:
int maxProfit(vector<int>& prices) {
vector<int> dp(2,0);
dp[0] = -prices[0];
for(int i=1; i<prices.size(); i++){
dp[0] = max(dp[0], dp[1]-prices[i]);
dp[1] = max(dp[1], prices[i]+dp[0]);
}
return dp[1];
}
};
55. 跳跃游戏
cpp
class Solution {
public:
bool canJump(vector<int>& nums) {
int cover = 0;
for(int i=0; i<=cover; i++){
if(i+nums[i]>cover){
cover = i+nums[i];
}
if(cover>=nums.size()-1) return true;
}
return false;
}
};
参考文章:代码随想录-55. 跳跃游戏
45.跳跃游戏II
cpp
class Solution {
public:
int jump(vector<int>& nums) {
if (nums.size() == 1) return 0;
int cover = 0;
int next_cover = 0;
int count = 0;
for(int i=0; i<=nums.size(); i++){
if(i+nums[i]>next_cover){
next_cover = i+nums[i];
}
if(i == cover){
count++;
cover = next_cover;
if(next_cover>=nums.size()-1){
return count;
}
}
}
return -1;
}
};
参考文章:代码随想录- 45.跳跃游戏II