Skip to content

Commit bc1f27a

Browse files
committed
修改文件: DynamicProgram/122-best-time-to-buy-and-sell-stock-ii.md
1 parent 0780fe4 commit bc1f27a

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
---
2+
title: 122-best-time-to-buy-and-sell-stock-ii
3+
tags: 新建,模板,小书匠
4+
grammar_cjkRuby: true
5+
---
6+
7+
8+
# problem
9+
[122-best-time-to-buy-and-sell-stock-ii](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/#/description)
10+
11+
# solution
12+
```cpp
13+
int maxProfit(vector<int>& prices) {
14+
//找到一段自增段;
15+
if (prices.empty()||prices.size() == 1)
16+
return 0;
17+
int maxElem = -1, minElem = -1, result = 0;
18+
while ((maxElem < (int)prices.size()) && (minElem < (int)prices.size()) )
19+
{
20+
//先找局部最小值;
21+
int i = maxElem + 1;
22+
for (; i < prices.size() - 1; i++)
23+
if (prices[i+1] > prices[i])
24+
break;
25+
minElem = i;
26+
int j = i + 1;
27+
for (; j < prices.size() -1; j++)
28+
if (prices[j+1] < prices[j])
29+
break;
30+
maxElem = j;
31+
if (maxElem > minElem && maxElem < (int)prices.size())
32+
result += prices[maxElem] - prices[minElem];
33+
}
34+
return result;
35+
}
36+
```

0 commit comments

Comments
 (0)