Cover image for Interview Classic 150 Questions P121 Best Time to Buy and Sell Stock

Interview Classic 150 Questions P121 Best Time to Buy and Sell Stock


Timeline

timeline

2025-10-01

init

array

Title:

Just maintain two values: one is the current lowest price, and the other is the historical maximum profit. Each time assume selling today, then find the historical lowest point before today. This historical lowest point does not require additional traversal; it is recorded along the way when considering each day.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <climits>

class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
int max_profit = 0;
int min_price = prices[0];
int i = 0;

for(i = 1; i<n;i++){
max_profit = std::max(max_profit, prices[i] - min_price); // Each time assume selling the stock on the i-th day
min_price = std::min(prices[i], min_price);
}

return max_profit;

}
};