File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed
24 - Dynamic Programming Problems/31 - Best Time to Buy and Sell Stock Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ int maxProfit (vector<int >& prices) {
4+ // Initialize the minimum price to the first day's price
5+ int mini = prices[0 ];
6+
7+ // Initialize the maximum profit to 0
8+ int profit = 0 ;
9+
10+ // Iterate through the price list starting from the second day
11+ for (int i = 1 ; i < prices.size (); i++) {
12+ // Calculate the potential profit if the stock is sold on the current day
13+ int diff = prices[i] - mini;
14+
15+ // Update the maximum profit if the current profit is higher
16+ profit = max (profit, diff);
17+
18+ // Update the minimum price seen so far
19+ mini = min (mini, prices[i]);
20+ }
21+
22+ // Return the maximum profit found
23+ return profit;
24+ }
25+ };
You can’t perform that action at this time.
0 commit comments