File tree Expand file tree Collapse file tree 4 files changed +78
-0
lines changed Expand file tree Collapse file tree 4 files changed +78
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int maxProfit (vector<int >& prices) {
4
+ vector<int > minPricesFromStart;
5
+ vector<int > maxPricesFromEnd;
6
+
7
+ int minPrice = INT_MAX;
8
+ for (int i = 0 ; i < prices.size (); i++){
9
+ minPrice = min (minPrice, prices[i]);
10
+ minPricesFromStart.push_back (minPrice);
11
+ }
12
+ int maxPrice = -1 ;
13
+ for (int i = prices.size ()-1 ; i >= 0 ; i--){
14
+ maxPrice = max (maxPrice, prices[i]);
15
+ maxPricesFromEnd.push_back (maxPrice);
16
+ }
17
+ reverse (maxPricesFromEnd.begin (), maxPricesFromEnd.end ());
18
+
19
+ int maxProfit = 0 ;
20
+ for (int i = 0 ; i < prices.size (); i++){
21
+ int currentProfit = maxPricesFromEnd[i] - minPricesFromStart[i];
22
+ maxProfit = max (maxProfit, currentProfit);
23
+ }
24
+ return maxProfit;
25
+ }
26
+ };
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int maxProfit (vector<int >& prices) {
4
+ int maxPrice = 0 ;
5
+ int minPrice = INT_MAX;
6
+ int maxProfit = 0 ;
7
+ for (int i = 0 ; i < prices.size (); i++) {
8
+ if (prices[i] < minPrice) {
9
+ minPrice = prices[i];
10
+ } else {
11
+ maxPrice = prices[i];
12
+ int currentProfit = maxPrice - minPrice;
13
+ maxProfit = max (maxProfit, currentProfit);
14
+ }
15
+ }
16
+ return maxProfit;
17
+ }
18
+ };
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int maxProfit (vector<int >& prices) {
4
+ int minPrice = INT_MAX;
5
+ int maxProfit = 0 ;
6
+ for (int i = 0 ; i < prices.size (); i++) {
7
+ if (prices[i] < minPrice) {
8
+ minPrice = prices[i];
9
+ } else {
10
+ maxProfit = max (maxProfit, prices[i] - minPrice);
11
+ }
12
+ }
13
+
14
+ return maxProfit;
15
+ }
16
+ };
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int maxProfit (vector<int >& prices) {
4
+ if (prices.empty ())abort ();
5
+
6
+ int minPrice = prices[0 ];
7
+ int currentProfit = 0 ;
8
+ for (int price: prices) {
9
+ if (price < minPrice) {
10
+ minPrice = price;
11
+ } else {
12
+ currentProfit = max (currentProfit, price - minPrice);
13
+ }
14
+ }
15
+
16
+ return currentProfit;
17
+ }
18
+ };
You can’t perform that action at this time.
0 commit comments