Description
You are given an array prices where prices[i] is the price of a given stock on the i t h i^{th} ith day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Examples
Example 1:
Input: prices = [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
Example 2:
Input: prices = [1]
Output: 0
Constraints:
1 <= prices.length <= 5000
0 <= prices[i] <= 1000
思路
这题其实我自己没思路,用的是discuss中一个感觉最能理解的思路(还有一个思路没能理解 ToT)
动态规划最基本的就是确定子问题,也就是确定需要维护的状态,这样才能设立状态转移方程,这道题与普通动态规划不同的一点就在于:他不是单个状态!
嗯对,他其实有3个状态
- s1可以通过buy操作转移到s2,也可以通过cooldown操作维持在s1
- s2可以通过sell操作转移到s3,也可以通过cooldown操作维持在s2
- s3只能通过cooldown操作转移到s1(因为sell后不能马上buy)
以一个更适合动态规划的思路说就是
- s1(i) 可以通过 s1(i-1) cooldown,也可以通过 s3(i-1) cooldown 获取
- s2(i) 可以通过 s1(i-1) buy,也可以通过 s2(i-1) cooldown 获取
- s3(i) 只能通过 s2(i) sell 获取
那么维护以上三个状态所使用的三个状态的转移方程为
s
1
(
i
)
=
max
(
s
1
(
i
−
1
)
,
s
3
(
i
−
1
)
)
s
2
(
i
)
=
max
(
s
2
(
i
−
1
)
,
s
1
(
i
−
1
)
−
m
o
n
e
y
(
i
)
)
s
3
(
i
)
=
s
2
(
i
−
1
)
+
m
o
n
e
y
(
i
)
\begin{aligned} s1(i) &= \max(s1(i-1),s3(i-1)) \\ s2(i) &=\max(s2(i-1), s1(i-1)-money(i)) \\ s3(i) &=s2(i-1)+money(i) \end{aligned}
s1(i)s2(i)s3(i)=max(s1(i−1),s3(i−1))=max(s2(i−1),s1(i−1)−money(i))=s2(i−1)+money(i)
初始化的话就是维护第0个时刻三个状态的数值,其实就分为2类,我在第0个时刻有没有购买呢?买了就处于s1(0),没买就处于s2(0)。至于s3(0),因为之前没有过购买操作,所以无法抛出,所以直接置为0
s
1
(
0
)
=
0
s
2
(
0
)
=
−
m
o
n
e
y
(
0
)
s
3
(
0
)
=
0
\begin{aligned} s1(0) &= 0\\ s2(0) &=-money(0) \\ s3(0) &=0 \end{aligned}
s1(0)s2(0)s3(0)=0=−money(0)=0
代码
class Solution {
public int maxProfit(int[] prices) {
int[] s1 = new int[prices.length];
int[] s2 = new int[prices.length];
int[] s3 = new int[prices.length];
s1[0] = 0;
s2[0] = -prices[0];
s3[0] = 0;
for(int i = 1; i < prices.length; i++){
s1[i] = Math.max(s1[i - 1], s3[i - 1]);
s2[i] = Math.max(s1[i - 1] - prices[i], s2[i - 1]);
s3[i] = s2[i - 1] + prices[i];
}
return Math.max(s1[prices.length - 1], Math.max(s2[prices.length - 1], s3[prices.length - 1]));
}
}