Stock Maximize Discussions | | HackerRank

Stock Maximize

  • + 1 comment

    Python 3

    The logic is that you start from the back, setting that as the highest value. THen you move back through the days. If the stock on that day is lower, then you know that it would make sense to buy it, to sell on the higher day... therefore your profit is the difference. If the stock on tht day is higher, then you wouldn't sell AND you have a new highest stock price.

    def stockmax(prices):
        P = prices[::-1]
        total = 0
        highest = P[0]
        for stock in P:
            if stock < highest:
                profit = highest - stock
                total += profit
            if stock > highest:
                highest = stock
        return total
    
    • + 0 comments

      Super simple and helpful explanation :)