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

2019-04-26  本文已影响0人  何学诚
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

上一篇下一篇

猜你喜欢

热点阅读