1. 程式人生 > >leetcode_122. Best Time to Buy and Sell Stock II 多次買賣股票,求交易的最大利潤

leetcode_122. Best Time to Buy and Sell Stock II 多次買賣股票,求交易的最大利潤

題目:

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