买卖股票的最佳时机 II
买卖股票的最佳时机 II 题目 给定一个数组,它的第i个元素是一支给定股票第i天的价格。 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多交易(多次买卖一支股票)。 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/ 思路 根据对题目的分析,可以采用贪心算法,即不考虑多天持有一支股票,每次只持有一天。只要第i天的价格比第i-1天高,我们就在第i-1天买入,第i天卖出。 注:可以在卖出当天再次买入股票 python代码 class Solution : def maxProfit ( self , prices : List [ int ] ) - > int : profit = 0 for i in range ( 1 , len ( prices ) ) : if prices [ i ] > prices [ i - 1 ] : profit += ( prices [ i ] - prices [ i - 1 ] ) return profit 相关知识点 range函数 执行结果 执行用时 : 56 ms, 在所有 Python3 提交中击败了89.01% 的用户 内存消耗 : 14.5 MB,