122.买卖股票的最佳时机Ⅱ
给你一个整数数组 prices,其中 prices[i] 表示某只股票第 i 天的价格。在每一天,你可以决定是否购买和、或售出股票。你在任何时候最多只能持有一股股票。你也可以先购买,然后在同一天出售。返回你能获得的最大利润。
贪心算法,找到局部最优,确保全局最优。我们将利润分解为每天,确保每天收获的利润为正利润,则在最终天得到的利润即为最大利润。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int profit = 0;
for (int i = 1; i < prices.size(); i++) {
profit += max(prices[i] - prices[i - 1], 0);
}
return profit;
}
};
计算每一天的利润,如果是正向利润,我们就在收集该天的利润,如果是负利润,则跳过,确保每一天买入卖出获得的利润对最终利润都是正向作用,从而确保在最终获得最大利润。
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.跳跃游戏Ⅱ
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;
}
}
return ans;
}
};