买卖股票的最佳时机

121. 买卖股票的最佳时机

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择某一天买入这只股票,并选择在未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。

示例 1:

输入:[7,1,5,3,6,4]
输出:5
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。

示例 2:

输入:prices = [7,6,4,3,1]
输出:0
解释:在这种情况下, 没有交易完成, 所以最大利润为 0。

提示:

1 <= prices.length <= 105
0 <= prices[i] <= 104

解题思路

方法一

暴力

选择最大差值,但是该方法超时了

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
//暴力
public int maxProfit(int[] prices) {
int res = 0;
for(int i = 0 ; i < prices.length; i++){
for(int j = i+1; j < prices.length; j++){
res = Math.max(res, prices[j]-prices[i]);
}
}
return res;
}
}
  • 时间复杂度:$O(n^2)$
  • 空间复杂度:$O(1)$

方法二

贪心

选取左端的最小值为买入点,右端的最大值为卖出点

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
//贪心
public int maxProfit(int[] prices) {
int res = 0;
int low = Integer.MAX_VALUE;
for(int i = 0 ; i < prices.length; i++){
low = Math.min(prices[i], low);
res = Math.max(prices[i] - low, res);
}
return res;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$

方法三

动态规划

1.确定dp数组及下标的含义

dp[i] [0] 表示第 i 天持有股票所得的最多现金

dp[i] [1] 表示第 i 天不持有股票的最多现金

这里的持有不代表当天买入,也可能昨天买入,今天保持持有的状态

2.确定递推公式

如果第i天持有股票即dp[i] [0], 那么可以由两个状态推出来

  • 第i-1天就持有股票,那么就保持现状,所得现金就是昨天持有股票的所得现金 即:dp[i - 1] [0]
  • 第i天买入股票,所得现金就是买入今天的股票后所得现金即:-prices[i]

那么dp[i] [0]应该选所得现金最大的,所以dp[i] [0] = max(dp[i - 1] [0], -prices[i]);

如果第i天不持有股票即dp[i] [1], 也可以由两个状态推出来

  • 第i-1天就不持有股票,那么就保持现状,所得现金就是昨天不持有股票的所得现金 即:dp[i - 1] [1]
  • 第i天卖出股票,所得现金就是按照今天股票佳价格卖出后所得现金即:prices[i] + dp[i - 1] [0]

同样dp[i] [1]取最大的,dp[i] [1] = max(dp[i - 1] [1], prices[i] + dp[i - 1] [0]);

3.初始化dp数组

由递推公式可知,都要从dp[0] [0] 和dp[0] [1] 推导出来

dp[0] [0] -= -prices[0] ,表示第0天就持有股票,买入股票的所剩金额为负数

dp[0] [1] = 0,表示第0天不持有股票

4.确定遍历顺序

从前往后遍历

dp数组的状态如图

image-20220607150454234

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int maxProfit(int[] prices) {
int[][] dp = new int[prices.length][2];
//dp[i][0] 表示第 i 天持有股票所得的最多现金
//dp[i][1] 表示第 i 天不持有股票的最多现金
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];
}
}

  • 时间复杂度:$O(n)$

  • 空间复杂度:$O(n)$

dp[i]只是依赖于dp[i - 1]的状态,可以使用滚动数组来节省空间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int maxProfit(int[] prices) {
int[] dp = new int[2];
//dp[0]表示当天持有股票的最大金额
//dp[1]表示当天不持有股票的最大金额
dp[0] = -prices[0];
dp[1] = 0;
for(int i = 1; i<prices.length; i++){
dp[0] = Math.max(dp[0], -prices[i]);
dp[1] = Math.max(dp[1], dp[0] + prices[i]);
}
return dp[1];
}
}
  • 时间复杂度:$O(n)$

  • 空间复杂度:$O(1)$


买卖股票的最佳时机
http://example.com/2023/01/28/算法/动态规划/24. 买卖股票的最佳时机/
作者
PALE13
发布于
2023年1月28日
许可协议