美文网首页
Leetcode122-Best Time to Buy and

Leetcode122-Best Time to Buy and

作者: LdpcII | 来源:发表于2017-09-20 11:00 被阅读0次

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

My Solution

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

Reference (转)

class Solution(object):
    def maxProfit(self, prices):
        return sum(max(prices[i + 1] - prices[i], 0) for i in range(len(prices) - 1))

相关文章

网友评论

      本文标题:Leetcode122-Best Time to Buy and

      本文链接:https://www.haomeiwen.com/subject/htgnsxtx.html