Leetcode #122. Best Time to Buy and Sell Stock II

题目

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[j]=max(v[j],prices[j]prices[i]+v[i1],v[j1])v[j]=max(v[j],prices[j]−prices[i]+v[i−1],v[j−1])
,大概意思是已经选定当前卖日为j,买日为i,股票票价是prices[i]或者prices[j],从第j日价格减去第i日价格加上第i-1日的收益判断是不是应该买,数组v存的是历史上这一天决策的最佳收益值,后面的v[j-1]代表说今天不买卖(v[j-1]+0)。
完整代码:
    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],那么

prices[j]prices[k+1]+prices[k]prices[i]>prices[j]prices[i]]=prices[j]prices[k+1]+prices[k+1]prices[i](128)(129)(128)prices[j]−prices[k+1]+prices[k]−prices[i]>prices[j]−prices[i]](129)=prices[j]−prices[k+1]+prices[k+1]−prices[i]

推广开来,你会发现,前面只要买,上升后一知道要下降就卖最后收益值就会最大化了。具体可以自己举下情况判断一下这个想法。
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. “

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值