[每日一题]122. best-time-to-buy-and-sell-stock-ii

1.这是一道找最优解的题目

用贪心算法就能解决。
遍历一次,如果val(i+1)>val(i)的话,记下这次收益。

122-best-time-to-buy-and-sell-stock-ii.png

链接:
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

2.题解:

就遍历一次,然后每次进行判断,O(n)复杂度

class Solution(object):
    def maxProfit(self, prices):
        val = 0
        for i in range(1,len(prices)):
            if prices[i-1] < prices[i]:
                val = val + prices[i]-prices[i-1]
        return val
3.完整代码

查看链接:
https://github.com/Wind0ranger/LeetcodeLearn/blob/master/7-greedy/122-best-time-to-buy-and-sell-stock-ii.py

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容