21 lines
583 B
Python
21 lines
583 B
Python
|
# 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
|