Python beat 100%


  • 2
    J
    def maxProfitSingle(prices):
        if len(prices) < 2: return 0
        buy = prices[0]
        sale = 0
        profit = 0
        for i in xrange(len(prices)):
            if prices[i] < buy: #if item lower than buy, set as buy
                buy = prices[i]
            elif prices[i] > buy: 
                sale = prices[i]  
                if sale - buy > profit:
                    profit = sale - buy
        if sale == 0: return 0
        return profit
    

  • 0
    B

    shall we just start with index 1 as we have already set prices[0] to buy?


Log in to reply
 

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