4
\$\begingroup\$

Question

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 \$N\$ 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?

Input

The first line contains the number of test cases \$T\$. \$T\$ test cases follow:

The first line of each test case contains a number \$N\$. The next line contains \$N\$ integers, denoting the predicted price of WOT shares for the next \$N\$ days.

Output

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

Constraints

\$1 <= T <= 10\$
\$1 <= N <= 50000\$

All share prices are between 1 and 100000

Code

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
class Solution{
public static void main(String[] args){
    Scanner stdin = new Scanner(System.in);
    int t = stdin.nextInt();
    for(int m=0;m<t;m++){
        long n = stdin.nextLong();
        long[] ar = new long[(int)n];
        for(int i=0;i<n;i++){
            ar[i] = stdin.nextLong();
        }
        long max = maximum(ar);
        System.out.println(max);
    }
}
public static long maximum(long[] ar){
    int j=0;
    long costPrice=0;
    long sellingPrice=0;
    int k=0;
    long max = maximumKey(j,ar);
    while(j<ar.length){
        if(ar[j]<max){
            costPrice += ar[j];
            j++;
        }
        else if(ar[j]==max){
            sellingPrice += ((j-k)*ar[j]);
            j++;
            k=j;
            max = maximumKey(j,ar);
        }            
    }
    return sellingPrice-costPrice;
}
    public static long maximumKey(int j, long[] ar){
        long max = 0;
        for(int i=j;i<ar.length;i++){
            if(max<ar[i])
                max = ar[i];
        }
            return max;
    }        
}

In the above code I didn't use DP. But this is supposed to be solved using DP with time complexity \$O(n)\$.

\$\endgroup\$
  • \$\begingroup\$ There is a well known way to do this O(N) time with dynamic if you could only hold on to 1 share at a time. However, I do not think that it is possible in this case (with as many shares as can be purchased), since the most profit would stem from buying all the way until the last global maximum (if it is duplicated), waiting until prices have fallen to the level of the next peak, and recursing. Repeatedly finding the global maximum will cause this to be a O(N^2) problem in the worst case (with constantly rising and falling prices, and diminishing maximums). \$\endgroup\$ – mleyfman Jul 24 '14 at 23:57
  • \$\begingroup\$ Yes my program is of n^2 level whearas as i saw people saying they were able to solve in O(n) time by using DP. Now how can this question be solved using DP hackerrank.com/challenges/stockmax \$\endgroup\$ – Torrtuga Jul 25 '14 at 1:15
  • \$\begingroup\$ Ah, there is indeed a special trick for determining next global max in O(1), see my answer below. \$\endgroup\$ – mleyfman Jul 25 '14 at 5:06
4
\$\begingroup\$

The trick to getting this problem in O(n) is some clever pre-processing.

Examples

Let's take 2 trials:

Trial 1: 1, 2, 3, 4, 5

Trail 2: 5, 4, 3, 2, 1

Obviously best case in Trial 1 is to buy for 4 days and sell on the 5th, for profit of 10. In Trial 2, there is no profit to be gained, because the price never increases, because there is never a higher maximum down the line.

Trick

This points towards the trick: starting from the end make a note of the maximum encountered thus far.

For Trial 1, the maximums are 5, 5, 5, 5, 5

For Trial 2, the maximums are the same as the prices

Let's try this for a more complex scenario: 10, 1, 9, 2, 8, 3, 7

The corresponding maximums would be: 10, 9, 9, 8, 8, 7, 7

Then, for every day that price < maximum, you should buy. If price = maximum, you should sell, and if price > maximum, wait it out.

Code

This yields the following code, assuming you parse the prices into a non-empty long[] named prices:

long[] maximums = new long[prices.length];
maximums[prices.length - 1] = prices[prices.length - 1];
// fill maximums array, from the end
for (int i = prices.length - 2; i >= 0; i--) {
    if (prices[i] > maximums[i + 1])
        maximums[i] = prices[i];
    else
        maximums[i] = maximums[i + 1];
}

// Trade!
long profit = 0;
for (int i = 0; i < prices.length; i++) {
    if (prices[i] < maximums[i]) {
        // BUY now and SELL at max
        profit += maximums[i] - prices[i]; 
    }
}
\$\endgroup\$
  • \$\begingroup\$ Got it.I was calculating the maximum everytime inside the for loop,instead i should have made an array storing the maximum value. \$\endgroup\$ – Torrtuga Jul 25 '14 at 16:36
  • \$\begingroup\$ @mleyfman Thanks your solution helped me.But i guess there is a slight mistake.if(price[i]>maximums[i-1]) should be if price[i]>maximums[i+1],and maximums[i]=maximums[i-1] should be maximums[i]=maximums[i+1]. Correct me if i am wrong \$\endgroup\$ – aakansha Jun 19 '15 at 7:43
  • \$\begingroup\$ Thanks for the trick and code. The idea is correct, however, some small typos are in your code which needed to be corrected when you fill out the maximums from the end: if (prices[i] > maximums[i + 1]) maximums[i] = prices[i]; else maximums[i] = maximums[i + 1]; \$\endgroup\$ – user103564 Apr 22 '16 at 6:50
  • \$\begingroup\$ @naz20z Thanks for pointing that out, updated answer to reflect it. \$\endgroup\$ – mleyfman Apr 30 '16 at 22:38
  • \$\begingroup\$ This can be optimized to be single-pass constant space: long max = Long.MIN_VALUE, profit = 0; for(int i = prices.length - 1; i >= 0; --i) if(prices[i] >= max) max = prices[i]; else profit += max - prices[i]; \$\endgroup\$ – Deduplicator Feb 14 '17 at 22:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.