Stock Maximize Discussions | | HackerRank

Stock Maximize

Sort by

recency

|

27 Discussions

|

  • + 0 comments

    Java O(n)

      public static long stockmax(List<Integer> prices) {
            long maxProfit = 0;
            int maxFuturePrice = 0;
    
            for (int i = prices.size() - 1; i >= 0; i--) {
                if (prices.get(i) > maxFuturePrice) {
                    maxFuturePrice = prices.get(i);
                }
                maxProfit += maxFuturePrice - prices.get(i);
            }
    
            return maxProfit;
        }
    
  • + 0 comments
    def stockmax(prices):
        last_price = prices[-1]
        max_profit = 0
        for key, price in enumerate(reversed(prices)):
            if not key:
                continue
            if price < last_price:
                max_profit += last_price - price
            else:
                last_price = price
        return max_profit
    
  • + 0 comments

    Java 8 solution using Recurssive method calls:

    public static long stockmax(List<Integer> prices) {
        // Write your code here
        // Find the max val of the list and find the index. If the index of max val is 0 then no profit can be made and return 0.
        // else profit can be made. Sell the stock at the max index.
        // Corner case, need to check the max index for the remaining sub-list after max index to verify the another opportunity.
        long profit = 0L;
    
        int maxIndex = prices.indexOf(Collections.max(prices));
        if(maxIndex == prices.size()-1){
            return getProfitFromSubList(prices);
        }
        else{
            List<Integer> subList1 = prices.subList(0,maxIndex+1);
            List<Integer> subList2 = prices.subList(maxIndex+1, prices.size());
    
            profit = getProfitFromSubList(subList1);
            profit += stockmax(subList2);
        }
    
        return profit;
    
    }//method
    
    public static long getProfitFromSubList(List<Integer> subList){
        long costPrice = 0L;
        int cnt = 0;
    
        for(int i =0; i < subList.size()-1; i++){
            costPrice += subList.get(i);
            cnt++;
        }
        long sellPrice = subList.get(subList.size()-1) * cnt;
        return sellPrice-costPrice;
    }
    
  • + 0 comments
    def stockmax(prices):
        # Write your code here
        x = max(prices)
        firstIndex = prices.index(x)
        if(firstIndex == 0):
            res = 0
        else:
            res = -1*sum(prices[0:firstIndex]) + firstIndex*x
        if(firstIndex+1 == len(prices)):
            return res
        else:
            return res + stockmax(prices[firstIndex+1:])
    
  • + 0 comments
    def stockmax(prices):
        profit = 0
        maxPrice = 0
        for price in prices[::-1]:
            if price > maxPrice:
                maxPrice = price
            else:
                profit += maxPrice - price
        return profit