Skip to content

Commit b7022bd

Browse files
authored
Merge pull request #77 from jaydev-431/patch-1
Refactor stock profit calculation methods
2 parents 2333c67 + 06cad1e commit b7022bd

1 file changed

Lines changed: 26 additions & 7 deletions

File tree

02_Dynamic-Programming/11. Buy and Sell Stock Problems/02. As Many Transactions As You Like.py

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,63 @@
11
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
22
# https://www.youtube.com/watch?v=nGJmxkUJQGs
33

4+
# --------------------------------------------------------------------------------------------
5+
# 1) TOP-DOWN DP (Memoization)
6+
# --------------------------------------------------------------------------------------------
7+
48
class Solution:
59
def maxProfit(self, prices: List[int]) -> int:
610
memo = {}
11+
712
def solve(i, can_sell):
8-
if i == len(prices):
13+
if i == len(prices):
914
return 0
10-
if (i, can_sell) in memo:
15+
if (i, can_sell) in memo:
1116
return memo[(i, can_sell)]
17+
1218
if can_sell == 1:
1319
profit = max(prices[i] + solve(i+1, 0), solve(i+1, 1))
1420
else:
1521
profit = max(-prices[i] + solve(i+1, 1), solve(i+1, 0))
22+
1623
memo[(i, can_sell)] = profit
1724
return profit
25+
1826
return solve(0, 0)
1927

20-
# Time: O(2 * N)
21-
# Space: O(N + N)
28+
# Time: O(2N)
29+
# Space: O(N)
30+
2231

23-
################################################################################################
32+
# --------------------------------------------------------------------------------------------
33+
# 2) BOTTOM-UP DP (Tabulation)
34+
# --------------------------------------------------------------------------------------------
2435

2536
class Solution:
2637
def maxProfit(self, prices: List[int]) -> int:
2738
n = len(prices)
2839
dp = [[0]*2 for _ in range(n+1)]
2940
dp[0][0] = -2**31
41+
3042
for i in range(1, n+1):
3143
for can_sell in range(2):
3244
if can_sell == 1:
3345
dp[i][can_sell] = max(prices[i-1] + dp[i-1][0], dp[i-1][1])
3446
else:
3547
dp[i][can_sell] = max(-prices[i-1] + dp[i-1][1], dp[i-1][0])
48+
3649
return dp[-1][1]
3750

38-
################################################################################################
51+
52+
# --------------------------------------------------------------------------------------------
53+
# 3) GREEDY (Optimized)
54+
# Tiny PR change: Added type hints
55+
# --------------------------------------------------------------------------------------------
56+
57+
from typing import List
3958

4059
class Solution:
41-
def maxProfit(self, prices):
60+
def maxProfit(self, prices: List[int]) -> int:
4261
res = 0
4362

4463
for i in range(len(prices) - 1):

0 commit comments

Comments
 (0)