Ridiculously simple answer in Python


  • 0
    A

    This is a pretty easy question I think. No programing difficulties. The idea is that you can sum the effects of the best operations for buying and selling by comparing everyday to the day before (it doesn't necessarily mean that you buy and sell everyday, but it's equivalent).

    It seems that this problem would be slightly more interesting if the interviewer wanted the indexes of the fewest buy/sell operations that give this profit. Well...

    class Solution:
        # @param prices, a list of integer
        # @return an integer
        def maxProfit(self, prices):
            p = 0
            for i in xrange(len(prices)-1):
                p += max(prices[i+1] - prices[i], 0)
            return p

  • 0
    X
    class Solution:
        # @param prices, a list of integer
        # @return an integer
        def maxProfit(self, prices):
            return sum( [prices[i+1] - prices[i]  for i in xrange(len(prices)-1) if prices[i+1] - prices[i] > 0] )

Log in to reply
 

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