[#1005] 添加leetcode题目 股票的最大利润二
This commit is contained in:
parent
8f24ffbc0d
commit
621f3adce9
50
docs/notes/69. 股票的最大利润二.md
Normal file
50
docs/notes/69. 股票的最大利润二.md
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
# 69. 股票的最大利润 二
|
||||||
|
|
||||||
|
## 题目链接
|
||||||
|
|
||||||
|
[Leetcode:Best Time to Buy and Sell Stock II](https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/564/)
|
||||||
|
|
||||||
|
## 题目描述
|
||||||
|
|
||||||
|
可以有任意次数买入和卖出,求最大收益。
|
||||||
|
|
||||||
|
```html
|
||||||
|
输入: [7,1,5,3,6,4]
|
||||||
|
输出: 7
|
||||||
|
解释:
|
||||||
|
- 第二天以1的价格买入,第三天以5的价格卖出.利润就是 5-1 = 4.
|
||||||
|
- 第四天以3的价格买入,第五天以6的价格卖出.利润就是 6-3 = 3.
|
||||||
|
- 所以总共利润就是4+3 = 7.
|
||||||
|
```
|
||||||
|
|
||||||
|
## 解题思路
|
||||||
|
|
||||||
|
使用峰谷策略
|
||||||
|
|
||||||
|
TODO: 添加图片 notes/pics/maxprofit2.png
|
||||||
|
|
||||||
|
```java
|
||||||
|
public int maxProfit(int[] prices) {
|
||||||
|
int i = 0;
|
||||||
|
int valley = prices[0];
|
||||||
|
int peak = prices[0];
|
||||||
|
int maxprofit = 0;
|
||||||
|
while (i < prices.length - 1) {
|
||||||
|
while (i < prices.length - 1 && prices[i] >= prices[i + 1])
|
||||||
|
i++;
|
||||||
|
valley = prices[i];
|
||||||
|
while (i < prices.length - 1 && prices[i] <= prices[i + 1])
|
||||||
|
i++;
|
||||||
|
peak = prices[i];
|
||||||
|
maxprofit += peak - valley;
|
||||||
|
}
|
||||||
|
return maxprofit;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>
|
BIN
notes/pics/maxprofit2.png
Normal file
BIN
notes/pics/maxprofit2.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 34 KiB |
Loading…
x
Reference in New Issue
Block a user