|
1 | 1 | # https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ |
2 | 2 | # https://www.youtube.com/watch?v=nGJmxkUJQGs |
3 | 3 |
|
| 4 | +# -------------------------------------------------------------------------------------------- |
| 5 | +# 1) TOP-DOWN DP (Memoization) |
| 6 | +# -------------------------------------------------------------------------------------------- |
| 7 | + |
4 | 8 | class Solution: |
5 | 9 | def maxProfit(self, prices: List[int]) -> int: |
6 | 10 | memo = {} |
| 11 | + |
7 | 12 | def solve(i, can_sell): |
8 | | - if i == len(prices): |
| 13 | + if i == len(prices): |
9 | 14 | return 0 |
10 | | - if (i, can_sell) in memo: |
| 15 | + if (i, can_sell) in memo: |
11 | 16 | return memo[(i, can_sell)] |
| 17 | + |
12 | 18 | if can_sell == 1: |
13 | 19 | profit = max(prices[i] + solve(i+1, 0), solve(i+1, 1)) |
14 | 20 | else: |
15 | 21 | profit = max(-prices[i] + solve(i+1, 1), solve(i+1, 0)) |
| 22 | + |
16 | 23 | memo[(i, can_sell)] = profit |
17 | 24 | return profit |
| 25 | + |
18 | 26 | return solve(0, 0) |
19 | 27 |
|
20 | | -# Time: O(2 * N) |
21 | | -# Space: O(N + N) |
| 28 | +# Time: O(2N) |
| 29 | +# Space: O(N) |
| 30 | + |
22 | 31 |
|
23 | | -################################################################################################ |
| 32 | +# -------------------------------------------------------------------------------------------- |
| 33 | +# 2) BOTTOM-UP DP (Tabulation) |
| 34 | +# -------------------------------------------------------------------------------------------- |
24 | 35 |
|
25 | 36 | class Solution: |
26 | 37 | def maxProfit(self, prices: List[int]) -> int: |
27 | 38 | n = len(prices) |
28 | 39 | dp = [[0]*2 for _ in range(n+1)] |
29 | 40 | dp[0][0] = -2**31 |
| 41 | + |
30 | 42 | for i in range(1, n+1): |
31 | 43 | for can_sell in range(2): |
32 | 44 | if can_sell == 1: |
33 | 45 | dp[i][can_sell] = max(prices[i-1] + dp[i-1][0], dp[i-1][1]) |
34 | 46 | else: |
35 | 47 | dp[i][can_sell] = max(-prices[i-1] + dp[i-1][1], dp[i-1][0]) |
| 48 | + |
36 | 49 | return dp[-1][1] |
37 | 50 |
|
38 | | -################################################################################################ |
| 51 | + |
| 52 | +# -------------------------------------------------------------------------------------------- |
| 53 | +# 3) GREEDY (Optimized) |
| 54 | +# Tiny PR change: Added type hints |
| 55 | +# -------------------------------------------------------------------------------------------- |
| 56 | + |
| 57 | +from typing import List |
39 | 58 |
|
40 | 59 | class Solution: |
41 | | - def maxProfit(self, prices): |
| 60 | + def maxProfit(self, prices: List[int]) -> int: |
42 | 61 | res = 0 |
43 | 62 |
|
44 | 63 | for i in range(len(prices) - 1): |
|
0 commit comments