122、买卖股票的最佳时机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、跳跃游戏
讲解:https://programmercarl.com/0055.%E8%B7%B3%E8%B7%83%E6%B8%B8%E6%88%8F.html
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;
}
};
45、跳跃游戏II
讲解:https://programmercarl.com/0045.%E8%B7%B3%E8%B7%83%E6%B8%B8%E6%88%8FII.html
class Solution {
public:
int jump(vector<int>& nums) {
if (nums.size() == 1) return 0;
int curDistance = 0; // 当前覆盖最远距离下标
int ans = 0; // 记录走的最大步数
int nextDistance = 0; // 下一步覆盖最远距离下标
for (int i = 0; i < nums.size(); i++) {
nextDistance = max(nums[i] + i, nextDistance); // 更新下一步覆盖最远距离下标
if (i == curDistance) { // 遇到当前覆盖最远距离下标
ans++; // 需要走下一步
curDistance = nextDistance; // 更新当前覆盖最远距离下标(相当于加油了)
if (nextDistance >= nums.size() - 1) break; // 当前覆盖最远距到达集合终点,不用做ans++操作了,直接结束
}
}
return ans;
}
};