leetcode/0121_best-time-to-buy-and-sell-stock/python3/solution.py

21 lines
583 B
Python
Raw Permalink Normal View History

2022-04-23 18:56:19 +00:00
# Time: O(N)
# Space: O(1)
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) < 1: return 0
i, j = 0, 1
max_profit = 0
while i <= j < len(prices):
max_profit = max(prices[j] - prices[i], max_profit)
# Buy low, sell high — so we need to keep moving i (like
# a buy pointer) if jth price is smaller than what ith is.
if prices[j] < prices[i]:
i = j
else:
j += 1
return max_profit