DSA Patterns (Multi-Lang)•Part 2: Arrays, Strings & Hash Maps (6 - 18)
Best Time to Buy and Sell Stock (I & II).
In Simple Words:
- Part I (One Transaction): Track
minPriceseen so far and updatemaxProfit = max(maxProfit, price - minPrice). - Part II (Unlimited Transactions): Accumulate all positive price differences
price[i] - price[i-1]greedily. - Time: $O(N)$ | Space: $O(1)$
Multi-Language SolutionsPython 3 • JavaScript • TypeScript • Java • C++
Switch tabs or choose Alldef maxProfitPartI(prices: list[int]) -> int:
min_price = float('inf')
max_p = 0
for p in prices:
min_price = min(min_price, p)
max_p = max(max_p, p - min_price)
return max_p
def maxProfitPartII(prices: list[int]) -> int:
profit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
profit += prices[i] - prices[i - 1]
return profit