best-time-to-buy-and-sell-stock py3

This commit is contained in:
2022-04-24 00:26:19 +05:30
parent ea19828ef3
commit 731af263a4
2 changed files with 45 additions and 0 deletions

View File

@@ -0,0 +1,20 @@
# 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