Best Time to Buy and Sell Stock
Easy · Sliding window
Jump to codeGiven daily prices, choose one buy day and a later sell day to maximize profit. You may make no transaction, giving profit zero.
Examples
Example 1
prices = [7,1,5,3,6,4]
Output: 5
Example 2
prices = [7,6,4,3,1]
Output: 0
Constraints
- 1 <= prices.length <= 100
- 0 <= prices[i] <= 100
Need a hint?
For a sale today, only the cheapest earlier price matters.
Asked in real interviews
Candidates reported versions of Best Time to Buy and Sell Stock from these company interviews. Some company questions are locked and open with Premium or XP.
- Compute drawdown, profit, and coin changeSquarepoint
- Compute Stock Profit with One or Unlimited TransactionsMeta
- Maximize stock profit with one or two tradesUber
Solution approach
Track the minimum price seen and the best profit. For each new day, compare today’s price minus that minimum with the best profit, then update the minimum. Initialize best profit to zero so falling prices never force a loss.
Complexity
O(n) time and O(1) extra space.
Python reference solution
def maxProfit(prices):
cheapest = float('inf')
best = 0
for price in prices:
best = max(best, price - cheapest)
cheapest = min(cheapest, price)
return best
JavaScript solution
function maxProfit(prices) {
let cheapest = Infinity, best = 0;
for (const price of prices) {
cheapest = Math.min(cheapest, price);
best = Math.max(best, price - cheapest);
}
return best;
}
Java solution
import java.util.*;
class Solution {
public int maxProfit(int[] prices) {
int cheapest = Integer.MAX_VALUE, best = 0;
for (int price : prices) {
cheapest = Math.min(cheapest, price);
best = Math.max(best, price - cheapest);
}
return best;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxProfit(vector<int> &prices) {
int cheapest = INT_MAX, best = 0;
for (int price : prices) {
cheapest = min(cheapest, price);
best = max(best, price - cheapest);
}
return best;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 9 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
7,
1,
5,
3,
6,
4
]
]5
[
[
7,
6,
4,
3,
1
]
]0
[
[
1,
2
]
]1
[
[
2,
1,
2,
0,
1
]
]1
[
[
3,
3,
5,
0,
0,
3,
1,
4
]
]4
Drafts are saved per language in this browser when storage is available.