Skip to content

Commit d20ea06

Browse files
Added Day-29 Solution
1 parent 50ce35d commit d20ea06

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'''
2+
Say you have an array for which the ith element is the price of a given stock on day i.
3+
4+
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
5+
6+
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
7+
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
8+
Example:
9+
10+
Input: [1,2,3,0,2]
11+
Output: 3
12+
Explanation: transactions = [buy, sell, cooldown, buy, sell]
13+
14+
15+
16+
'''
17+
18+
class Solution:
19+
def maxProfit(self, prices: List[int]) -> int:
20+
n = len(prices)
21+
dpsell_1 = 0
22+
dpbuy_1 = 0
23+
dpbuy_2 = 0
24+
for i in range(n-1, -1, -1):
25+
# if buy
26+
op1 = -prices[i] + dpsell_1
27+
op2 = dpbuy_1
28+
old_dpbuy_1 = dpbuy_1
29+
dpbuy_1 = max(op1, op2)
30+
31+
op1 = prices[i] + dpbuy_2
32+
op2 = dpsell_1
33+
dpsell_1 = max(op1, op2)
34+
dpbuy_2 = old_dpbuy_1
35+
return dpbuy_1

0 commit comments

Comments
 (0)