【LeetCode】 123. Best Time to Buy and Sell Stock III 买卖股票的最佳时机 III(Hard)(JAVA)
题目地址: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
题目描述:
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
Input: prices = [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
Example 2:
Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
Example 4:
Input: prices = [1]
Output: 0
Constraints:
- 1 <= prices.length <= 10^5
- 0 <= prices[i] <= 10^5
题目大意
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。
注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
解题方法
这一题比较难的是:上一次可能持有股票,也可能不持有股票。索性就分两种状态来判断
- 采用动态规划的方法,重要的是找出 dp 函数和转移方程
- 用 dp[i][j][k] 表示动态函数:i 表示 股票的位置;j 表示交易的最大次数;k = 0, 表示当前位置不持有股票, k = 1, 表示当前位置持有股票
- 找出转移方程
- 如果 i = 0, 也就是第 0 个位置,不管最大交易几次,当前位置最大值都为 0,如果持有股票的话 dp[0][j][1] = -prices[i]
- 如果 j = 0, 也就是 当前交易最大次数为 0,当前位置最大值都为 0,如果持有股票的话,就需要和上一次比较哪一个更小了
- 如果当前不持有股票(求出所有情况的最大值):1. 上一次持有股票 + 当前的股票价值(需要少一次最大交易次数);2. 上一次也不持有(最大交易次数和上次相同)
- 如果当前持有股票(求出所有情况的最大值):1. 上一次不持有股票 - 当前的股票价值;2. 上一次持有股票
class Solution {
public int maxProfit(int[] prices) {
// [i][j][0]: no stock, [i][j][1]: has stock
int[][][] dp = new int[prices.length][3][2];
for (int i = 0; i < prices.length; i++) {
for (int j = 0; j < dp[0].length; j++) {
if (i == 0) {
dp[i][j][0] = 0;
dp[i][j][1] = -prices[i];
} else if (j == 0) {
dp[i][j][0] = 0;
dp[i][j][1] = Math.max(-prices[i], dp[i - 1][j][1]);
} else {
dp[i][j][0] = Math.max(dp[i - 1][j][0], dp[i - 1][j - 1][1] + prices[i]);
dp[i][j][1] = Math.max(dp[i - 1][j][0] - prices[i], dp[i - 1][j][1]);
}
}
}
return dp[prices.length - 1][2][0];
}
}
执行耗时:135 ms,击败了6.91% 的Java用户
内存消耗:64.6 MB,击败了14.26% 的Java用户
![](https://i-blog.csdnimg.cn/blog_migrate/6c56d31f951aece27c5faae608dfac2e.jpeg#pic_center)