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. 跳跃游戏
力扣题目链接
class Solution {
public:
bool canJump(vector<int>& nums) {
int cover = 0;
if (nums.size() == 1) {
return true;
}
for (int i = 0; i <= cover; ++i) {
cover = max(i + nums[i], cover);
if (cover >= nums.size() - 1) {
return true;
}
}
return false;
}
};
45.跳跃游戏 II
力扣题目链接
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;
}
};