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 2fefa40

Browse files
raof01azl397985856
authored andcommitted
best-time-to-buy-and-sell-stock: add C++ solution (azl397985856#45)
1 parent e00d032 commit 2fefa40

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

‎problems/121.best-time-to-buy-and-sell-stock.md‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ Explanation: In this case, no transaction is done, i.e. max profit = 0.
4040

4141
## 代码
4242

43-
语言支持:JS,Python
43+
语言支持:JS,Python,C++
4444

4545
JS Code:
4646

@@ -135,7 +135,28 @@ Memory Usage: 14.1 MB, less than 10.26% of Python3 online submissions for Best T
135135
"""
136136
```
137137

138-
138+
C++ Code:
139+
```c++
140+
/**
141+
* 系统上C++的测试用例中的输入有[],因此需要加一个判断
142+
*/
143+
class Solution {
144+
public:
145+
int maxProfit(vector<int>& prices) {
146+
if (prices.empty()) return 0;
147+
auto min = prices[0];
148+
auto profit = 0;
149+
for (auto i = 1; i < prices.size(); ++i) {
150+
if (prices[i] > prices[i -1]) {
151+
profit = max(profit, prices[i] - min);
152+
} else {
153+
min = std::min(min, prices[i]);;
154+
}
155+
}
156+
return profit;
157+
}
158+
};
159+
```
139160
140161
141162

0 commit comments

Comments
(0)

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