leetcode_122 best time to buy and sell stock ii

假设有一个数组,它的第 i 个元素是一个给定的股票在第 i 天的价格。

设计一个算法来找到最大的利润。你可以完成尽可能多的交易(多次买卖股票)。然而,你不能同时参与多个交易(你必须在再次购买前出售股票)。

“””
贪心算法:这一题不再限制买卖的次数,只要价格比前一天高就可以前一天买入、后一天卖出了。
“””

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
max_profit = 0

for i in range(1, len(prices)):
if prices[i] - prices[i - 1] > 0:
max_profit += prices[i] - prices[i - 1]

return max_profit