You are given an array prices where prices[i] is the price of a given stock on the ( i )-th day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Two-Pointer Technique
l (left) set to the first day (buy day) and r (right) set to the second day (sell day).max_profit to 0.r pointer is within the bounds of the prices array:
r day is greater than the price on the l day:
prices[r] and prices[l].max_profit with the maximum of the current max_profit and the newly calculated profit.r day is not greater than the price on the l day:
l pointer to the r day (consider the current r day as the new potential buy day).r pointer to the next day.max_profit.class Solution:
def maxProfit(self, prices: List[int]) -> int:
l, r = 0, 1
max_profit = 0
while r < len(prices):
if prices[r] > prices[l]:
profit = prices[r] - prices[l]
max_profit = max(profit, max_profit)
else:
l = r
r += 1
return max_profit