1.1 Best Time to Buy and Sell Stock II
拆分利润即可,如果后一天比前一天大,立刻买。如果一样或小,则不买,当天利润记为0.
所以,循环部分也可以写成:result += max(prices[i] - prices[i - 1], 0);
但,以下是我的代码:
class Solution {
public int maxProfit(int[] prices) {
int res = 0;
for(int i = 0; i < prices.length-1; ++i){
int j = i+1;
if(prices[j] > prices[i]){
res += prices[j] - prices[i];
}
}
return res;
}
}
1.2 Best Time to Buy and Sell Stock
顺手把这个也做了,思路差不多。
class Solution {
public int maxProfit(int[] prices) {
int res = 0, tmp = 0;
for(int i = 0; i < prices.length-1; ++i){
tmp = Math.max(tmp + prices[i+1] - prices[i], 0);
res = Math.max(res, tmp);
}
return res;
}
}
看每一格还剩的最大步数即可。
class Solution {
public boolean canJump(int[] nums) {
int maxStep = nums[0];
for(int i = 1; i < nums.length; ++i){
if(maxStep == 0) return false;
maxStep = Math.max(maxStep-1, nums[i]);
}
return true;
}
}
不能理解卡哥的算法,但这个方法很棒!从后往前找!!
class Solution {
public int jump(int[] nums) {
int steps = 0, pos = nums.length-1;
while(pos > 0){
for(int i = 0; i < nums.length; ++i){
if(i + nums[i] >= pos){
pos = i;
++steps;
break;
}
}
}
return steps;
}
}
文章介绍了如何解决股票最佳买卖时机问题,包括两种不同策略:一种是找到连续两天中利润最大的差价,另一种是在考虑交易费用的情况下求最大利润。同时,文章还讨论了两种跳跃游戏问题,关注于计算能到达终点的最小步数,分别从前向后和从后向前的策略进行求解。
773

被折叠的 条评论
为什么被折叠?



