Skip to content

Commit 5f1e329

Browse files
authored
Create main.cpp
1 parent a56b9fa commit 5f1e329

File tree

1 file changed

+25
-0
lines changed
  • 24 - Dynamic Programming Problems/31 - Best Time to Buy and Sell Stock

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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+
};

0 commit comments

Comments
 (0)