卖萌的弱渣

I am stupid, I am hungry.

Best Time to Buy and Sell Stock 2

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).

Solution

  • 统计递增序列的和
(Best-Time-to-Buy-and-Sell-Stock2.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) < 2:
            return 0
        # 递增序列起点
        buy = 0
        # 递增序列终点
        sell = 0
        ret = 0
        for i in range(1,len(prices)):
            if prices[i] < prices[sell]:
                ret += prices[sell]-prices[buy]
                buy = i
                sell = i
            else:
                sell = i

        # 1,2,3,4
        if sell>buy:
            ret += prices[sell]-prices[buy]

        return ret