春招第一步,算法伴我行
题目描述:
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
如:[7,1,5,3,6,4],最大利润为:7(2买3卖,4买5卖可以实现最大利润)
同时有要求:不能同时进行多次交易,即每次只能先买后卖。
思路:
类似于121,动态规划解决,但是现在的状态只有两个,不像上一题的三种状态,现在一旦没有股票都可以买入:
dp[i][0]:当前可以买入
dp[i][1]:当前可以卖出
动态规划解决:
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:return 0
dp = [[0]*2 for _ in range(len(prices))]
dp[0][0], dp[0][1] = 0, -prices[0]
for i in range(1, len(prices)):
dp[i][0] = max(dp[i-1][0], dp[i-1][1]+prices[i])
dp[i][1] = max(dp[i-1][0]-prices[i], dp[i-1][1])
return dp[-1][0]
类似于第二种解法,这道题也可以使用同样的思路:从头遍历,只要后面的比前面的大,就卖出,然后继续买入。
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:return 0
current, profit = prices[0], 0
for price in prices[1:]:
if price-current>0:
profit += price-current
current = price
else:
current = price
return profit
另外一种更简洁的写法,不需要额外变量:
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:return 0
profit = 0
for i in range(1, len(prices)):
if prices[i]>prices[i-1]:
profit += (prices[i]-prices[i-1])
return profit