题目要求

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

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

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

            

        

        

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄