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 (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

题目分析及思路

给出一个数组,第i个元素是第i天的股票价格。需要设计一个算法找到最大的利润。可以进行多次交易,但必须是以一买一卖这样的顺序进行的,不可在再次买之前还未卖掉之前买的股票。可以遍历整个数组,若价格上升,则记录上升的差值。将所有差值求和就是最后的最大利润。

python代码

class Solution:

    def maxProfit(self, prices: List[int]) -> int:

        maxprofit = 0

        for i in range(1,len(prices)):

            if prices[i] > prices[i-1]:

                maxprofit += prices[i] - prices[i-1]

        return maxprofit

            

        

        

 

posted on 2019-04-15 09:45  锋上磬音  阅读(84)  评论(0编辑  收藏  举报