Stock Maximize Discussions | Algorithms | HackerRank
  • + 2 comments

    Not a DP problem. Solution is just to iterate backwards. If our current price is greater than the max price, update the max price. If it is smaller, then there is profit to be made - and that profit is the difference between the current price and max price (as we would offload all shares on the max price day).

    def stockmax(prices):
        profit = 0
        maxPrice = 0
        for price in prices[::-1]:
            if price > maxPrice:
                maxPrice = price
            else:
                profit += maxPrice - price
        return profit