main idea: each price can be choosen as buy point, only price later than buy point can be use as sell point. Since there is only one transaction allowed, we need to mantain 2 variables: minPrice and maxProfit
# time O(N) space(1)
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# edge case :
if len(prices) < 2:
return 0
minPrice = prices[0]
maxProfit = 0
for p in prices:
# compare and update minP
minPrice = min(minPrice,p)
# compare and upate maxP with current price - minP
if p - minPrice > maxProfit:
maxProfit = p - minPrice
return maxProfit