题目
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
题意
这道题是前面一道题的升级版,前面一道题是说只买卖一次,求出这里面最好的一次选择即收益最大,这一次是说你可以多次买卖,但是要求手上没有股票了才能再买
想法
分享一下一个之前的想法,之前想过用动态规划做,
完整代码:
v = [0 for i in range(len(prices))]
for i in range(len(prices)):
for j in range(i+1,len(prices)):
if i!=0:#有历史收益
v[j] = max(v[j], prices[j]-prices[i]+v[i-1],v[j-1])
else:#没有历史收益
v[j] = max(v[j], prices[j]-prices[i],v[j-1])
print(v)
return max(v)
小样本上这个是能跑的,但是由于是两层循环,这个出题人要求的时间是O(n),应该是,这就超时了,后来在讨论区学习了一下,意识到这道题是直接O(n)做的,它有一个考虑,如果在一个序列里,假设起始是i,中间有一天k,prices[k]>prices[k+1],这意味着,会存在一个逆差,可能你会说万一后面有一个j,远远大于第k天的股价,那现在卖不是亏了么,这个时候仔细看会发现如果prices[k]>prices[k+1],那么
推广开来,你会发现,前面只要买,上升后一知道要下降就卖最后收益值就会最大化了。具体可以自己举下情况判断一下这个想法。
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
profit = 0
for i in range(1, len(prices)):
if prices[i]>prices[i-1]:
profit += prices[i]-prices[i-1]
return profit
PS:评论区里有位答主提到这是他去面高盛集团时的面试题
“This question is indeed the interview question I encountered interviewing with Goldman Sachs. “