121. Best Time to Buy And Sell Stock - Explanation
Description
You are given an integer array prices where prices[i] is the price of NeetCoin on the ith day.
You may choose a single day to buy one NeetCoin and choose a different day in the future to sell it.
Return the maximum profit you can achieve. You may choose to not make any transactions, in which case the profit would be 0.
Example 1:
Input: prices = [10,1,5,6,7,1]
Output: 6Explanation: Buy prices[1] and sell prices[4], profit = 7 - 1 = 6.
Example 2:
Input: prices = [10,8,7,5,2]
Output: 0Explanation: No profitable transactions can be made, thus the max profit is 0.
Constraints:
1 <= prices.length <= 1000 <= prices[i] <= 100
Topics
Recommended Time & Space Complexity
You should aim for a solution with O(n) time and O(1) space, where n is the size of the input array.
Hint 1
A brute force solution would be to iterate through the array with index i, considering it as the day to buy, and trying all possible options for selling it on the days to the right of index i. This would be an O(n^2) solution. Can you think of a better way?
Hint 2
You should buy at a price and always sell at a higher price. Can you iterate through the array with index i, considering it as either the buying price or the selling price?
Hint 3
We can iterate through the array with index i, considering it as the selling value. But what value will it be optimal to consider as buying point on the left of index i?
Hint 4
We are trying to maximize profit = sell - buy. If the current i is the sell value, we want to choose the minimum buy value to the left of i to maximize the profit. The result will be the maximum profit among all. However, if all profits are negative, we can return 0 since we are allowed to skip doing transaction.
Prerequisites
Before attempting this problem, you should be comfortable with:
- Arrays - Iterating through elements and tracking values
- Two Pointers - Using multiple pointers to track buy and sell positions
- Greedy Algorithms - Making locally optimal choices (tracking minimum buy price) for global optimization
1. Brute Force
Intuition
The brute-force approach checks every possible buy–sell pair.
For each day, we pretend to buy the stock, and then we look at all the future days to see what the best selling price would be.
Among all these profits, we keep the highest one.
Algorithm
- Initialize
res = 0to store the maximum profit. - Loop through each day
ias the buy day. - For each buy day, loop through each day
j > ias the sell day. - Calculate the profit
prices[j] - prices[i]and updateres. - Return
resafter checking all pairs.
Time & Space Complexity
- Time complexity:
- Space complexity:
2. Two Pointers
Intuition
We want to buy at a low price and sell at a higher price that comes after it.
Using two pointers helps us track this efficiently:
lis the buy day (looking for the lowest price)ris the sell day (looking for a higher price)
If the price at r is higher than at l, we can make a profit — so we update the maximum.
If the price at r is lower, then r becomes the new l because a cheaper buying price is always better.
By moving the pointers this way, we scan the list once and always keep the best buying opportunity.
Algorithm
- Set two pointers:
l = 0(buy day)r = 1(sell day)maxP = 0to track maximum profit
- While
ris within the array:- If
prices[r] > prices[l], compute the profit and updatemaxP. - Otherwise, move
ltor(we found a cheaper buy price). - Move
rto the next day.
- If
- Return
maxPat the end.
Time & Space Complexity
- Time complexity:
- Space complexity:
3. Dynamic Programming
Intuition
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.
Algorithm
- 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.
Time & Space Complexity
- Time complexity:
- Space complexity:
Common Pitfalls
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.
# Wrong: selling before buying
for i in range(len(prices)):
for j in range(i): # j < i means selling earlier
profit = prices[j] - prices[i] # BackwardsReturning 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.
# Wrong: can return negative
return maxPrice - minPrice # Could be negative if maxPrice found before minPrice
Sign in to join the discussion