# Determining maximum profit to be made from selling shares

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)$.

• 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). – mleyfman Jul 24 '14 at 23:57
• 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 – Torrtuga Jul 25 '14 at 1:15
• Ah, there is indeed a special trick for determining next global max in O(1), see my answer below. – mleyfman Jul 25 '14 at 5:06

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];
}


• 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]; – Deduplicator Feb 14 '17 at 22:30