1、题目描述
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易 k = +infinity(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
2、贪心法,易懂建议
如果今天的价格比明天的价格低,就今天买,明天卖(贪心)
class Solution(object):
def maxProfit(self, prices):
n = len(prices)
if n == 0:
return 0
res = 0
for i in range(1, n):
if prices[i] - prices[i-1] > 0:
res += prices[i] - prices[i-1]
return res
3、通用版代码详解
同类型题 DP-LeetCode121. 买卖股票的最佳时机
class Solution(object):
def maxProfit(self, prices):
# dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i])
# dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i])
n = len(prices)
dp_i_0 = 0
dp_i_1 = float("-inf")
for i in range(n):
temp = dp_i_0
dp_i_0 = max(dp_i_0, dp_i_1 + prices[i])
dp_i_1 = max(dp_i_1, temp - prices[i])
return dp_i_0
prices = [7,1,5,3,6,4]
s = Solution()
print(s.maxProfit(prices))