假设你有一个数组prices,长度为n,其中prices[i]是某只股票在第i天的价格,请根据这个价格数组,返回买卖股票能获得的最大收益
1. 你可以多次买卖该只股票,但是再次购买前必须卖出之前的股票
2. 如果不能获取收益,请返回0
3. 假设买入卖出均无手续费
数据范围:
,
要求:空间复杂度
,时间复杂度 )
进阶:空间复杂度
,时间复杂度
[8,9,2,5,4,7,1]
7
在第1天(股票价格=8)买入,第2天(股票价格=9)卖出,获利9-8=1 在第3天(股票价格=2)买入,第4天(股票价格=5)卖出,获利5-2=3 在第5天(股票价格=4)买入,第6天(股票价格=7)卖出,获利7-4=3 总获利1+3+3=7,返回7
[5,4,3,2,1]
0
由于每天股票都在跌,因此不进行任何交易最优。最大收益为0。
[1,2,3,4,5]
4
第一天买进,最后一天卖出最优。中间的当天买进当天卖出不影响最终结果。最大收益为4。
总天数不大于200000。保证股票每一天的价格在[1,100]范围内。
class Solution: def maxProfit(self , prices: List[int]) -> int: n = len(prices) #dp[i][0]表示某一天不持股到该天为止的最大收益,dp[i][1]表示某天持股,到该天为止的最大收益 dp = [[0] * 2 for i in range(n)] #第一天不持股,总收益为0 dp[0][0] = 0 #第一天持股,总收益为减去该天的股价 dp[0][1] = -prices[0] #遍历后续每天,状态转移 for i in range(1, n): # 第i天不持股有两种情况,第一种昨天就没有买股票,第二种昨天卖出了股票(这里一直保存最大收益,整个过程下来相当于只买了一次) dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]) # 第i天持股有两种情况,第一种昨天就持股,第二种昨天不持股,但是今天买入了(这里相当于寻找最最小值了) dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i]) #最后一天不持股,到该天为止的最大收益 return dp[n - 1][0]
class Solution: def maxProfit(self , prices: List[int]) -> int: # write code here if len(prices) == 0&nbs***bsp;len(prices) == 1: return 0 prices.insert(0, float('inf')) result = 0 start = -1 for i in range(1, len(prices)): if i == len(prices)-1: if prices[i] >= prices[i-1] and start != -1 and prices[i] > prices[start]: result += prices[i] - prices[start] break if prices[i] < prices[i-1] and prices[i] <= prices[i+1]: start = i if prices[i] >= prices[i-1] and prices[i] > prices[i+1]: if start != -1: result += prices[i] - prices[start] start = -1 return result
class Solution: def maxProfit(self , prices: List[int]) -> int: # write code here res = 0 pivot = 0 index = 1 while index < len(prices): if prices[index] > prices[pivot]: while index + 1 < len(prices) and prices[index+1] > prices[index]: index += 1 res += (prices[index] - prices[pivot]) pivot = index + 1 index = index + 2 else: index += 1 pivot += 1 return res
class Solution: def maxProfit(self , prices: List[int]) -> int: # write code here if not prices: return 0 dp=[0]*len(prices) min_price=prices[0] res=[] for i in range(1,len(prices)): min_price=min(prices[i],min_price) if dp[i-1]<prices[i]-min_price: res.append(prices[i]-min_price) min_price=prices[i] dp[i]=0 else: dp[i]=dp[i-1] return sum(res)
class Solution: def maxProfit(self , prices ): max_out = 0 for i in range(len(prices)-1): max_out += max(prices[i+1] - prices[i],0) return max_out
class Solution: def maxProfit(self , prices ): # write code here takein = 0 if prices == []: return 0 if len(prices) == 1: return 0 if prices[1]>prices[0]: takein = -prices[0] i = 1 while i < len(prices)-1: if (prices[i]<=prices[i-1])&(prices[i]<prices[i+1]): takein -= prices[i] if (prices[i]>prices[i-1])&(prices[i]>=prices[i+1]): takein += prices[i] i += 1 if prices[-1]>prices[-2]: takein += prices[-1] return takein