Track minimum stock price seen so far and maximum profit achievable by selling at current price (profit = price - min_price).
class Solution:
def maxProfit(self, prices: list[int]) -> int:
l, r = 0, 1
max_p = 0
while r < len(prices):
if prices[l] < prices[r]:
profit = prices[r] - prices[l]
max_p = max(max_p, profit)
else:
l = r
r += 1
return max_p
class Solution {
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for (int price : prices) {
if (price < minPrice) {
minPrice = price;
} else if (price - minPrice > maxProfit) {
maxProfit = price - minPrice;
}
}
return maxProfit;
}
}