class Solution {
public:
int maxProfit(vector<int>& prices) {
int profit;
int total = 0;
//把前后2天的收益都记录下来, 然后把收益为正的都加起来就是最大利润
for (int i = 1; i < prices.size(); i++) {
profit = prices[i] - prices[i-1];
if (profit > 0) {
total += profit;
}
}
return total;
}
};
class Solution {
public:
bool canJump(vector<int>& nums) {
int n = nums.size();
int k = 0; //k表示累计能跳到的最大距离吧
for (int i = 0; i < n; ++i){
if (i > k) return false; // i > k 表示不能成功跳到最后一个位置
k = max(k, i+ nums[i]);
}
//如果成功跳过该循环,则表示能成功跳到最后一个位置
return true;
}
};
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) return ans;
}
}
return ans;
}
};