122买卖股票的最佳时机II

题目:给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii

法一:自己的代码

思路:贪心算法,由于不限制交易次数,所以所有上升的都可以加入最后的结果中,每次都把今天和昨天的作差,如果为正就加入结果中,最后所有正值的和即为结果。

from typing import List
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        for i,j in enumerate(prices[1:]):
            a = prices[i+1] - prices[i]
            if a > 0:
                prices[i] = a
            else:
                prices[i] = 0
        return sum(prices[:-1])
if __name__ == '__main__':
    duixiang = Solution()
    a = duixiang.maxProfit([7,1,5,3,6,4])
    # a = duixiang.maxProfit([5])
    print(a)
View Code

ttt

原文地址:https://www.cnblogs.com/xxswkl/p/12313362.html