代码随想录day28 122.买卖股票的最佳时机 II 、 55. 跳跃游戏 、45.跳跃游戏 II
122.买卖股票的最佳时机 II
class Solution {
public:
int maxProfit(vector<int>& prices) {
int sum = 0;
for (int i = 0; i < prices.size() - 1; i++) {
if (prices[i + 1] > prices[i]) {
sum += prices[i + 1] - prices[i];
}
}
return sum;
}
};
55. 跳跃游戏
class Solution {
public:
bool canJump(vector<int>& nums) {
int cover = 0;
for (int i = 0; i <= cover; i++) {
cover = max(nums[i] + i, cover);
if (cover >= nums.size() - 1) {
return true;
}
}
return false;
}
};
45.跳跃游戏 II
自己写的性能好像不太好
class Solution {
public:
int jump(vector<int>& nums) {
if (nums.size() == 1) return 0;
int cover = 0;
int size = 0;
int num = 0;
for (int i = 0; i <= cover;) {
size = cover;
for (int j = i; j <= size; j++) {
cover = max(j + nums[j], cover);
}
num++;
if (cover >= nums.size() - 1) {
break;
}
i = size + 1;
}
return num;
}
};
卡哥的方法更好
class Solution {
public:
int jump(vector<int>& nums) {
if (nums.size() == 1) return 0;
int curDistance = 0;
int nextDistance = 0;
int num = 0;
for (int i = 0; i < nums.size() - 1; i++) {
nextDistance = max(nums[i] + i, nextDistance);
if (i == curDistance) {
num++;
curDistance = nextDistance;
}
}
return num;
}
};