力扣第26天----第122题、第55题、第45题
一、第122题–买卖股票的最佳时机 II
赚钱的时候,把每天赚的钱加起来,就是最终的钱。没有任何难度!
class Solution {
public:
int maxProfit(vector<int>& prices) {
int result = 0;
for(int i = 1 ; i < prices.size(); i++){
if (prices[i] - prices[i-1] >0) result += prices[i] - prices[i-1];
}
return result;
}
};
二、第55题–跳跃游戏
这个题,属于见过就会做。实现上没难度,分析起来花点时间,下次见到类似的能做出来。核心就是:1)根据i + nums[i]做是否满足的判断;2)for循环end的位置更新为max(end, i + nums[i])。
class Solution {
public:
bool canJump(vector<int>& nums) {
if (nums.size() == 1) return true;
int end = 0;
for(int i =0; i<=end; i++){
//cout << i + nums[i] << endl;
if (i + nums[i] >= nums.size() - 1) return true;
end = max(end, i + nums[i]);
}
return false;
}
};
三、第45题–跳跃游戏 II
有点难,看了答案才做出来的。逻辑不好梳理,希望下次做,能做出来。
class Solution {
public:
int jump(vector<int>& nums) {
if(nums.size() == 1) return 0;
int count = 0;
int cur_range = 0;
int next_range = 0;
for (int i =0; i < nums.size()-1; i++){
next_range = max(i + nums[i], next_range);
if(i == cur_range){
cout << i <<endl;
cur_range = next_range;
count++;
if(next_range > nums.size()) break;
}
}
return count;
}
};