您的位置:首页 > 其它

leetcode_122. Best Time to Buy and Sell Stock II 多次买卖股票,求交易的最大利润

2016-11-16 11:18 537 查看
题目:

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock
before you buy again).

题意:

给定数组prices,数组元素i代表股票第i天的价格。假设可以多次买卖股票,问最大收益是多少。(在卖股票之前必须先买回股票)

代码:

class Solution(object):

    def maxProfit(self, prices):

        """

        :type prices: List[int]

        :rtype: int

        """

        

        n = len(prices)

        

        if n < 2 :

            return 0

        else :

            res = 0      #存储收益

            i = 0

            while i < n-1 :     #遍历每一天的价格

                if prices[i+1] > prices[i] :       #如果是上升的,则加到res中,最后res即为所有上升子序列的和

                    res += prices[i+1] - prices[i]

                i += 1

            

            return res

笔记:

题目说明可以多次买卖,但是同一时间只能有一股在手里。
这样就可以在每次上升子序列之前买入,在上升子序列结束的时候卖出。相当于能够获得所有的上升子序列的收益。

参考:http://blog.csdn.net/doc_sgl/article/details/11908197
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐