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 Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments