Best Time to Buy and Sell Stock II
Problem Summary
(Write in your own words, not copied from LeetCode. This forces comprehension.)
- Find maximum profit, given list of prices
- Restriction is that you have to buy/sell each day
Key Observations
(Patterns, constraints, or hints in the problem statement.)
- Have to sell it or buy stock each day -> fixed window of size 1
- Calculate profit if sell price > buy price otherwise skip
Main Concepts Used
(Mark the CS concepts or algorithms used.)
Time & Space Complexity
- Time:
→ Reason: Iterating through each item once - Space:
→ Reason: Not storing a copy of the array
Code
class Solution:
def maxProfit(self, prices: List[int]) -> int:
prev = None
totalProfit = 0
for price in prices:
if prev != None and price > prev:
profit = price - prev
totalProfit += profit
prev = price
return totalProfit
Common Mistakes / Things I Got Stuck On
if prev and ...:will fail because prev can be of value- use explicit check
prev != None
- use explicit check