best-time-to-buy-and-sell-stock py3
This commit is contained in:
20
0121_best-time-to-buy-and-sell-stock/python3/solution.py
Normal file
20
0121_best-time-to-buy-and-sell-stock/python3/solution.py
Normal 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
|
||||
Reference in New Issue
Block a user