Skip to content

Commit db1163b

Browse files
authored
Merge pull request #6 from colorbox/121
Add solved codes for `121. Best Time to Buy and Sell Stock`
2 parents f4201ed + 72d4df2 commit db1163b

File tree

4 files changed

+78
-0
lines changed

4 files changed

+78
-0
lines changed

121/1.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
};

121/2.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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+
};

121/3.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
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+
};

121/4.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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+
};

0 commit comments

Comments
 (0)