Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e838cd2

Browse files
Add C++ implementation
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent d5f5f97 commit e838cd2

File tree

1 file changed

+42
-0
lines changed
  • 0123_best_time_to_buy_and_sell_stock_iii

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
class Solution {
6+
public:
7+
int maxProfit(vector<int>& prices) {
8+
if (prices.size() == 0) {
9+
return 0;
10+
}
11+
12+
int max_diff = 0;
13+
int min_price = prices[0];
14+
vector<int> left_profits(prices.size());
15+
for (int i = 1; i < prices.size(); i++) {
16+
if (prices[i] < min_price) {
17+
min_price = prices[i];
18+
} else {
19+
int diff = prices[i] - min_price;
20+
max_diff = max(diff, max_diff);
21+
}
22+
left_profits[i] = max_diff;
23+
}
24+
25+
int total = 0;
26+
max_diff = 0;
27+
int right_profit = 0;
28+
int max_price = prices[prices.size() - 1];
29+
for (int i = prices.size() - 2; i >= 0; i--) {
30+
if (prices[i] > max_price) {
31+
max_price = prices[i];
32+
} else {
33+
int diff = max_price - prices[i];
34+
right_profit = max(diff, right_profit);
35+
}
36+
int profit = left_profits[i] + right_profit;
37+
total = max(profit, total);
38+
}
39+
40+
return total;
41+
}
42+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /