mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2026-02-02 18:39:09 +08:00
Update
This commit is contained in:
34
problems/0122.买卖股票的最佳时机II.md
Normal file
34
problems/0122.买卖股票的最佳时机II.md
Normal file
@@ -0,0 +1,34 @@
|
||||
## 链接
|
||||
https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
|
||||
|
||||
## 思路
|
||||
|
||||
首先要知道第0天买入,第3天卖出的利润:prices[3] - prices[0],相当于(prices[3] - prices[2]) + (prices[2] - prices[1]) + ()prices[1] - prices[0])
|
||||
|
||||
那么根据prices可以得到每天的利润序列:(prices[i] - prices[i - 1]).....(prices[1] - prices[0])。
|
||||
|
||||
可以发现,我们需要收集每天的正利润就可以,收集正利润的区间,就是股票买卖的区间,而我们只需要关注最终利润就可以了,不需要记录区间。
|
||||
|
||||
**这就是贪心所贪的地方,只收集正利润**。
|
||||
|
||||
如图:
|
||||
|
||||
<img src='../pics/122.买卖股票的最佳时机II.png' width=600> </img></div>
|
||||
|
||||
对应C++代码如下:
|
||||
|
||||
```
|
||||
class Solution {
|
||||
public:
|
||||
int maxProfit(vector<int>& prices) {
|
||||
int result = 0;
|
||||
for (int i = 1; i < prices.size(); i++) {
|
||||
result += max(prices[i] - prices[i - 1], 0);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
> 我是[程序员Carl](https://github.com/youngyangyang04),组队刷题可以找我,本文[leetcode刷题攻略](https://github.com/youngyangyang04/leetcode-master)已收录,更多[精彩算法文章](https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzUxNjY5NTYxNA==&action=getalbum&album_id=1485825793120387074&scene=173#wechat_redirect)尽在:[代码随想录](https://img-blog.csdnimg.cn/20200815195519696.png),期待你的关注!
|
||||
|
||||
Reference in New Issue
Block a user