leetcode @python 122. Best Time to Buy and Sell Stock II

题目链接

https://leetcode.com/problems/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).

题目大意

给定不同交易日的股票价格,可以进行多次的交易,但同一时间只能做一次交易

解题思路

若后一天的价格比前一天的价格高,可以计算一次交易,以此累加收益值

代码

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) <= 1:
            return 0
        profit = 0
        for i in range(1, len(prices)):
            if prices[i] - prices[i - 1] > 0:
                profit += prices[i] - prices[i - 1]
        return profit 
posted @ 2016-04-01 18:57  slurm  阅读(184)  评论(0编辑  收藏  举报