Best Time to Buy and Sell Stock
Easy · Sliding Window · Explanation and code example
Dynamic Programming
How it works
As we scan through the prices, we keep track of two things:
- The lowest price so far → this is the best day to buy.
- The best profit so far → selling today minus the lowest buy price seen earlier.
At each price, we imagine selling on that day.
The profit would be:
current price – lowest price seen so far
We then update:
- the maximum profit,
- and the lowest price if we find a cheaper one.
This way, we make the optimal buy–sell decision in one simple pass.
Steps
- Initialize:
minBuyas the first pricemaxP = 0for the best profit
- Loop through each price
sell:- Update
maxPwithsell - minBuy. - Update
minBuyif we find a smaller price.
- Update
- Return
maxPafter scanning all days.
Complexity
- Time complexity:
O(n) - Space complexity:
O(1)
Things to watch for
Selling Before Buying
The sell day must come after the buy day. Calculating prices[i] - prices[j] where j > i means you're selling in the past, which is invalid.
Returning Negative Profit
If prices only decrease, the maximum profit is 0 (don't trade), not a negative number. Always ensure the result is at least 0.
Python code example
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
maxP = 0
minBuy = prices[0]
for sell in prices:
maxP = max(maxP, sell - minBuy)
minBuy = min(minBuy, sell)
return maxP
C++ code example
class Solution {
public:
int maxProfit(vector<int>& prices) {
int maxP = 0;
int minBuy = prices[0];
for (int& sell : prices) {
maxP = max(maxP, sell - minBuy);
minBuy = min(minBuy, sell);
}
return maxP;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.