CS-Notes/docs/notes/63. 股票的最大利润.md

37 lines
1020 B
Java
Raw Normal View History

2019-11-02 12:07:41 +08:00
# 63. 股票的最大利润
2019-11-03 23:57:08 +08:00
## 题目链接
[Leetcode121. Best Time to Buy and Sell Stock ](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/)
2019-11-02 12:07:41 +08:00
## 题目描述
可以有一次买入和一次卖出买入必须在前求最大收益
2019-12-06 00:29:51 +08:00
<div align="center"> <img src="pics/42661013-750f-420b-b3c1-437e9a11fb65.png" width="220px"> </div><br>
2019-11-02 12:07:41 +08:00
## 解题思路
使用贪心策略假设第 i 轮进行卖出操作买入操作价格应该在 i 之前并且价格最低
```java
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0)
return 0;
int soFarMin = prices[0];
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
soFarMin = Math.min(soFarMin, prices[i]);
maxProfit = Math.max(maxProfit, prices[i] - soFarMin);
}
return maxProfit;
}
```
2019-11-02 14:39:13 +08:00
2019-11-02 17:33:10 +08:00
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>