Skip to content

Commit 1a58283

Browse files
authored
Merge pull request #327 from Stackingrule/dev
feat:add Solution.cpp for 0121. Best Time to Buy and Sell Stock
2 parents 788f2a4 + ca54a1c commit 1a58283

File tree

1 file changed

+17
-0
lines changed
  • solution/0100-0199/0121.Best Time to Buy and Sell Stock

1 file changed

+17
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
public:
3+
int maxProfit(vector<int>& prices) {
4+
const int n = prices.size();
5+
if (n < 1) return 0;
6+
vector<int> min_prices(n);
7+
vector<int> max_profit(n);
8+
min_prices[0] = prices[0];
9+
max_profit[0] = 0;
10+
for (int i = 1; i < n; ++i) {
11+
min_prices[i] = min(min_prices[i - 1], prices[i]);
12+
max_profit[i] = max(max_profit[i - 1], prices[i] - min_prices[i - 1]);
13+
}
14+
15+
return max_profit[n - 1];
16+
}
17+
};

0 commit comments

Comments
 (0)