7-liner in Python, beats 99%


  • 3
    class Solution(object):
        def maxProfit(self, p):
            if not p: return 0
            sell, buyd, n, minp, maxp = [0], [0], len(p), p[0], p[-1]
            for i in range(1, n):
                minp, maxp = min(minp, p[i]), max(maxp, p[n-i-1])
                sell.append(max(sell[i-1], p[i] - minp))
                buyd.append(max(buyd[i-1], maxp - p[n-i-1]))
            return max(sell[i] + buyd[n-i-1] for i in range(n))
    
    
    # 198 / 198 test cases passed.
    # Status: Accepted
    # Runtime: 56 ms
    

  • 0
    R

    @agave
    thanks ! Cool code !


Log in to reply
 

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