122.买卖股票的最佳时机II
题目链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/submissions/
代码:
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() == 1)
return 0;
int result;
int tmp;
for(int i = 1 ; i < prices.size(); i++)
{
tmp = prices[i] - prices[i-1];
if(tmp > 0)
result += tmp;
}
return result;
}
};
这是个脑筋急转弯吧哈哈哈哈
55. 跳跃游戏
题目链接:https://leetcode.cn/problems/jump-game/submissions/
代码:
class Solution {
public:
bool canJump(vector<int>& nums) {
if(nums.size() == 1)
return true;
int cover = 0;
for(int i = 0; i <= cover;i++)
{
cover = max(cover,i+nums[i]);
if(cover >= nums.size()-1)
return true;
}
return false;
}
};
45.跳跃游戏II
题目链接:https://leetcode.cn/problems/jump-game-ii/submissions/
代码一:
class Solution {
public:
int jump(vector<int>& nums) {
int curDistant = 0; //当前步骤范围
int nextDistant = 0; //下一步范围
int step = 0;
if(nums.size() == 1)
return 0;
for(int i = 0; i < nums.size(); i++)
{
nextDistant = max(nextDistant,i+nums[i]);
if(curDistant == i)
{
if(curDistant < nums.size() - 1)
{
step ++;
curDistant = nextDistant;
if(nextDistant >= nums.size() - 1)
break;
}else break;
}
}
return step;
}
};
代码二:
class Solution {
public:
int jump(vector<int>& nums) {
int curDistant = 0; //当前步骤范围
int nextDistant = 0; //下一步范围
int step = 0;
if(nums.size() == 1)
return 0;
for(int i = 0; i < nums.size()-1; i++)
{
nextDistant = max(nextDistant,i+nums[i]);
if(i == curDistant)
{
step++;
curDistant = nextDistant;
}
}
return step;
}
};
思路都差不多 但是我想不出。。。