We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents 2f1621f + dd39b08 commit 45fcbe1Copy full SHA for 45fcbe1
Arrays/Buy And Sell Stocks 3.cpp
@@ -0,0 +1,29 @@
1
+int maxProfit(vector<int>& prices) {
2
+ int n = prices.size();
3
+ if(n <= 1)
4
+ return 0;
5
+ if(n == 2) {
6
+ return max((prices[1] - prices[0]), 0);
7
+ }
8
+
9
+ vector<int> secondMax(n,0);
10
11
+ int maxPrice = prices[n-1];
12
+ int maxProfit = 0;
13
+ for(int i=n-2;i>=0;i--) {
14
+ maxProfit = max(maxProfit, maxPrice - prices[i]);
15
+ secondMax[i] = maxProfit;
16
+ maxPrice = max(maxPrice, prices[i]);
17
18
19
+ int minPrice = prices[0];
20
+ int ans = 0;
21
+ for(int i=1;i<n;i++) {
22
+ int currentProfit = prices[i] - minPrice;
23
+ minPrice = min(minPrice, prices[i]);
24
+ ans = max(ans,currentProfit);
25
+ if(i != n-1)
26
+ ans = max(ans, currentProfit + secondMax[i+1]);
27
28
+ return ans;
29
AltStyle によって変換されたページ (->オリジナル) / アドレス: モード: デフォルト 音声ブラウザ ルビ付き 配色反転 文字拡大 モバイル
0 commit comments