Stock Maximize HackerRank Solution

In this Stock Maximize HackerRank solution, Your algorithms have become so good at predicting the market that you now know what the share price of Wooden Orange Toothpicks Inc. (WOT) will be for the next number of days.

Each day, you can either buy one share of WOT, sell any number of shares of WOT that you own, or not make any transaction at all. What is the maximum profit you can obtain with an optimum trading strategy?

Example

Buy one share day one, and sell it day two for a profit of . Return .

No profit can be made so you do not buy or sell stock those days. Return .

Function Description

Complete the stockmax function in the editor below.

stockmax has the following parameter(s):

  • prices: an array of integers that represent predicted daily stock prices

Returns

  • int: the maximum profit achievable

Input Format

The first line contains the number of test cases .

Each of the next  pairs of lines contain:
– The first line contains an integer , the number of predicted prices for WOT.
– The next line contains n space-separated integers , each a predicted stock price for day .

Constraints

Output Format

Output  lines, each containing the maximum profit which can be obtained for the corresponding test case.

Sample Input

STDIN       Function
-----       --------
3           q = 3
3           prices[] size n = 3
5 3 2       prices = [5, 3, 2]
3           prices[] size n = 3
1 2 100     prices = [1, 2, 100]
4           prices[] size n = 4
1 3 1 2     prices =[1, 3, 1, 2]

Sample Output

0
197
3

Explanation

For the first case, there is no profit because the share price never rises, return .
For the second case, buy one share on the first two days and sell both of them on the third day for a profit of .
For the third case, buy one share on day 1, sell one on day 2, buy one share on day 3, and sell one share on day 4. The overall profit is .

Stock Maximize HackerRank solution

I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.

Problem Solution in Python

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

Problem Solution in C#

public static long stockmax(List<int> prices)
    {        
        int n = prices.Count;        
        int[] maxFromFuture = new int[n];
         
        int max = prices[n-1];
        for(int i=n-1; i>=0; i--)
        {
            max = Math.Max( prices[i] , max );
            maxFromFuture[i] = max;
        }
        long res = 0;
        for(int i = 0; i < n; i++)
        {
            res += (maxFromFuture[i] - prices[i]);
        }
                     
        return res;        
    }
}

Problem Solution in JavaScript

function stockmax(prices) {
    let [max, expense,stocks]  = [0,0,0];
    // Start from the end of the list
    for(let i = prices.length - 1; i>=0; i--)
     //finding the max to sell
      if(max< prices[i]){
        if(stocks > 0){
          // sell before next max;
          expense += stocks * max;
          stocks = 0;
        }
        // set up new max afte selling;
        max = prices[i];
      }
      else {
        //buy stocks, calc expense;
        expense -= prices[i];
        stocks++;
      }  
   
    expense += stocks * max;
    return expense;
}

Problem Solution in C++

long stockmax(vector<int> prices) {
long prof=0;
    int i=0,n=prices.size();
    int maxsofar=prices[n-1];
    for(int i=n-1;i>=0;i--){
        if(prices[i]>maxsofar){
            maxsofar=prices[i];
        }
        prof+=maxsofar-prices[i];
    }
    return prof;
}

Problem Solution in Java

public static long stockmax(List<Integer> prices) {
    // Write your code here
        int max = prices.size() -1;
        long profit = 0L;
       
        for(int i = max - 1; i >= 0; i--) {
            Integer iValue = prices.get(i);
            Integer maxValue = prices.get(max);
           
            if(iValue < maxValue) {
                profit += (maxValue - iValue);
            } else {
                max = i;
            }
        }


        return profit;
    }
Solve original Problem on HackerRank here. Checkout more HackerRank Problems

Leave a Comment