
121. 买卖股票的最佳时机
给你一个数组价格,其中prices[i]是给定股票第i天的价格。
您想通过选择某一天购买一只股票并选择未来的另一天出售该股票来最大化您的利润。
返回您可以从本次交易中获得的最大利润。如果您无法获得任何利润,请返回0.
示例1:
输入:价格 = [7,1,5,3,6,4]
输出:5
说明:第 2 天买入(价格 = 1),第 5 天卖出(价格 = 6),利润 = 6-1 = 5。
请注意,不允许在第 2 天买入并在第 1 天卖出,因为您必须在卖出之前买入。
示例2:
输入:价格 = [7,6,4,3,1]
输出:0
说明:在这种情况下,没有进行任何交易,最大利润 = 0.
限制:
1 0 原始页面
方法一、贪心算法
public int maxprofit(int[] prices) {
if(prices.length == 0){
return 0;
}
int profit = 0;
int buy = prices[0];
for(int i=1; i=prices[i]){
buy = prices[i];
}else{
profit = math.max(profit, prices[i]-buy);
}
}
return profit;
}
时间 o(n) 空间 o(1)
方法2 动态规划
public int maxprofit(int[] prices) {
if(prices.length == 0){
return 0;
}
// 2 means we have 2 different status (have owned stock or not )
int[][] dp = new int[prices.length][2];
// if we want to own the stock we should pay for the specific price
dp[0][0] = -prices[0];
for(int i=1; i
时间 o(n) 空间 o(n)
动态规划比贪心算法更通用,因为它不仅适用于特定问题。
方法2.1(提高空间复杂度)
public int maxprofit(int[] prices) {
if(prices.length == 0){
return 0;
}
// 2 means we have 2 different status (have owned stock or not )
int[] dp = new int[2];
// if we want to own the stock we should pay for the specific price
dp[0] = -prices[0];
for(int i=1; i
这里要小心,我们应该先处理 dp[1],因为它将使用之前的 dp[0] 而不是更新后的 dp[0]。
122. 买卖股票的最佳时机 ii
给你一个整数数组prices,其中prices[i]是给定股票在第i天的价格。
每天,您都可以决定购买和/或出售股票。您在任何时候最多只能持有一股股票。但是,您可以购买并在同一天立即出售。
找到并返还你能获得的最大利润。
示例1:
输入:价格 = [7,1,5,3,6,4]
输出:7
说明:第 2 天买入(价格 = 1),第 3 天卖出(价格 = 5),利润 = 5-1 = 4。
然后在第4天买入(价格=3)并在第5天卖出(价格=6),利润=6-3=3.
总利润为 4 + 3 = 7.
示例2:
输入:价格 = [1,2,3,4,5]
输出:4
说明:第 1 天买入(价格 = 1),第 5 天卖出(价格 = 5),利润 = 5-1 = 4。
总利润为4.
示例3:
输入:价格 = [7,6,4,3,1]
输出:0
说明:没有办法赚取正利润,所以我们从来不买股票来实现最大利润0。
限制:
1
0
public int maxprofit(int[] prices) {
if(prices.length <1){
return 0;
}
int[][] dp = new int[prices.length][2];
dp[0][0] = -prices[0];
for(int i=1; i
滚动数组方法
public int maxprofit(int[] prices) {
if(prices.length <1){
return 0;
}
int[] dp = new int[2];
dp[0] = -prices[0];
for(int i=1; i
123. 买卖股票的最佳时机 iii
给你一个数组价格,其中prices[i]是给定股票第i天的价格。
找到你能获得的最大利润。您最多可以完成两笔交易。
注意:您不得同时进行多项交易(即您必须先卖出股票才能再次购买)。
示例1:
输入:价格 = [3,3,5,0,0,3,1,4]
输出:6
说明:第 4 天买入(价格 = 0),第 6 天卖出(价格 = 3),利润 = 3-0 = 3。
然后在第7天买入(价格=1)并在第8天卖出(价格=4),利润=4-1=3.
示例2:
输入:价格 = [1,2,3,4,5]
输出:4
说明:第 1 天买入(价格 = 1),第 5 天卖出(价格 = 5),利润 = 5-1 = 4。
请注意,您不能在第一天买入,在第二天买入并随后卖出,因为您同时进行多项交易。再次购买之前必须先出售。
示例3:
输入:价格 = [7,6,4,3,1]
输出:0
说明:在这种情况下,没有进行任何交易,即最大利润 = 0.
限制:
1
0
public int maxProfit(int[] prices) {
int transactions = 2;
int[][] dp = new int[prices.length][transactions*2+1];
for(int i=1; i<=transactions; i++){
dp[0][i*2-1] = -prices[0];
}
for(int i=1; i










