[leetcode: Python]122. Best Time to Buy and Sell Stock 2

来源:互联网 发布:手机淘宝设置货到付款 编辑:程序博客网 时间:2024/06/17 06:39

题目:
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).
题意:
这道题的第一个版本是要求只能买卖一次。
第二个版本也就是本题,对买卖次数无要求,但是,必须再买下一只股票前,把手里的先卖掉。

方法一:性能49ms

class Solution(object):    def maxProfit(self, prices):        """        :type prices: List[int]        :rtype: int        """        profit = 0        for i in range(len(prices)-1):            if prices[i] < prices[i+1]:                profit += prices[i+1] - prices[i]        return profit

方法二:性能39ms

class Solution(object):    def maxProfit(self, prices):        """        :type prices: List[int]        :rtype: int        """        if not prices:            return 0        p = 0         res = []        for i in range(1,len(prices)):            if prices[i] > prices[i-1]:                res.append(prices[i] - prices[i-1])        return sum(res) if res else 0
0 0
原创粉丝点击