总结
● 122.买卖股票的最佳时机II
● 55. 跳跃游戏
● 45.跳跃游戏II
122.买卖股票的最佳时机II
// 买卖股票
// 统计相邻两天的买卖利润
// 统计最大利润
// 优化 减少空间复杂度到O(1),仅使用一个profit变量统计总利润
int maxProfits(vector<int>& prices) {
// 寻找利润和最大值
int profit = 0;
for (int i = 1; i < prices.size(); ++i) {
if ( prices[i] - prices[i - 1] > 0 )
profit += prices[i] - prices[i - 1];
}
return profit;
}
55. 跳跃游戏
题目:55. 跳跃游戏
思路:
判断能否跳跃到数组的末尾,遍历数组更新能够跳跃的最远距离,如果覆盖了整个数组,则可以结束了
bool isJumpToEnd2(vector<int>& nums) {
int maxStep = 0;
for (int i = 0; i <= maxStep; ++i) {
// 更新下一步可以跳到的范围
maxStep = max(maxStep, i + nums[i]);
if (maxStep >= nums.size() - 1) return true;
}
return false;
}
45.跳跃游戏II
题目:45.跳跃游戏II
本题是计算抵达数组末尾的最小跳跃次数,需要使用两个变量记录下一步可以跳跃的最大距离和当前可以跳跃的最大距离,如果i抵达当前跳跃的最大距离,则更新当前的最大跳跃距离,并将跳跃次数加1,直到覆盖了整个数组
int minJumpToEndStep(vector<int>& nums) {
// 数组值为1
if (nums.size() == 1) return 0;
int nextStepRange = 0, ret = 0, currentRange = 0;
for (int i = 0; i < nums.size(); ++i) {
// 更新可以跳跃的最远距离
nextStepRange = max(i + nums[i], nextStepRange);
if (i == currentRange) {
ret += 1;
currentRange = nextStepRange;
// 满足了就退出
if (currentRange >= nums.size() - 1) break;
}
}
return ret;
}