Clear 1-line Python Solution


  • 28
    W

    Basically, if tomorrow's price is higher than today's, we buy it today and sell tomorrow. Otherwise, we don't. Here is the code:

    class Solution(object):
        def maxProfit(self, prices):
            return sum(max(prices[i + 1] - prices[i], 0) for i in range(len(prices) - 1))

  • 1
    A

    wtf this is insane lol


  • 0
    M

    sorry for duplicated comment (I left it in another solution), but I think this approach fails to condition:
    However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again)
    since you are buying and selling on the same day


  • 1
    W

    Hi maxym, firstly, this condition means that you cannot hold more than one transaction at any time. My solution does not contradict with this - I am selling everything before buying anything. Secondly, just in case you haven't noticed, this kind of transaction (selling and buying on the same day) is redundant. For example, if you buy on day 1, sell on day 2, buy on day 2 and sell on day 3, the profit is exactly the same as buying on day 1 and selling on day 3. Hope this explanation makes sense to you.


  • 0
    M

    Hi, wz2326, thanks for comment. You are right, I over complicated restrictions ;)
    About redundancy, in my java solution I do tracking of price gradient and if it changes from increasing to decreasing I sell, otherwise I buy at lowest price.

    public int maxProfit(int[] prices) {
            int d = -1, l = prices.length, maxProfit = 0, buy = 0;
            for (int p = 0; p < l - 1; p++) {
                int sig = (int) Math.signum(prices[p + 1] - prices[p]);
                if (d > 0 && sig < 0) {
                    maxProfit += prices[p] - buy;
                }
                if (d < 0 && sig > 0) {
                    buy = prices[p];
                }
                d = sig == 0 ? d : sig;
            }
            if (d > 0) {
                maxProfit += prices[l - 1] - buy;
            }
            return maxProfit;
        }
    

  • 0

    have a question:
    what if prices = [1,2,3,4].then your answer will be 3,but I think the best profit is 4 ( (3-1)+(4-2) )


  • 3
    W

    Hi 李佑平, please note that you can hold at most one transaction at a time.


  • 2
    S

    the question states that "you must sell the stock before you buy again"


  • 0
    R

    Very pythonic


  • 0
    K

    I have to say that it's brilliant.


  • 0
    Y

    bro, this solution is insane!


  • 0
    Z

    Here's my (sort of) 1-liner using a little helper to get a pairwise iterator

    from itertools import tee
    
    def pairwise(iterable):
        a,b = tee(iterable)
        next(b, None)
        return zip(a,b)
    
    class Solution(object):
        def maxProfit(self, prices):
            """
            :type prices: List[int]
            :rtype: int
            """
            return sum(y-x if y>x else 0 for x,y in pairwise(prices))
    

  • 0
    C

    @wz2326 What does this exactly mean? if we were given price = [1,2,3,4], then if we buy 1 share at day1, buy the 2nd share at day2, then sell 1 share at day3, and sell the other share at day4, totally get 4 profits, which conditions of the problem is violated? Or should the description " you may not engage in multiple transactions at the same time " be interpreted as the following: a complete transaction is defined as buy and sell (I reverse engineering to understand the definition for this problem), so this implies that if you want to buy a share, you must have sold the previous share. Hence, you can't buy at day1 and then buy another share at day2, as you have not sold your share bought on day1. Is my understanding correct?


  • 0
    S

    Why we can't short sell a stock today, if we know it will be cheaper tomorrow?


  • 0
    Y

    well, you can do this if you don't care about the transaction fee lol


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.