1 买卖股票的最佳时机
题目
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
代码
class Solution {
public int maxProfit(int[] prices) {
int low=Integer.MAX_VALUE;
int result=0;
for(int i=0;i<prices.length;i++){
low=Math.min(low,prices[i]);
result=Math.max(result,prices[i]-low);
}
return result;
}
}
class Solution {
public int maxProfit(int[] prices) {
if(prices.length==0) return 0;
int[][] dp=new int[prices.length][2];
dp[0][0]=-prices[0];
dp[0][1]=0;
for(int i=1;i<prices.length;i++){
dp[i][0]=Math.max(dp[i-1][0],-prices[i]);
dp[i][1]=Math.max(dp[i-1][1],dp[i-1][0]+prices[i]);
}
return dp[prices.length-1][1];
}
}
总结
本题股票只能买卖一次。
贪心感觉更简单点。动态规划还是挺麻烦的。
2 买卖股票的最佳时机ii
题目
给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
返回 你能获得的 最大 利润 。
代码
class Solution {
public int maxProfit(int[] prices) {
if(prices.length==0) return 0;
int[][] dp=new int[prices.length][2];
dp[0][0]=-prices[0];
dp[0][1]=0;
for(int i=1;i<prices.length;i++){
dp[i][0]=Math.max(dp[i-1][0],dp[i-1][1]-prices[i]);
dp[i][1]=Math.max(dp[i-1][1],dp[i-1][0]+prices[i]);
}
return dp[prices.length-1][1];
}
}
总结
本题一只股票多次买卖。
解决了我上面的疑问,为什么买卖一次是-prices[i],而不是dp[i-1][1]-prices[i]
。