I was asked this question while interviewing for a startup and saw this again in the recent contest at
Code Sprint:systems
**The question :
You are
0.Start from end of array so that no need to recurse
1. smax = maximum stock price from the list
2.Then find the profit by assuming you have bought all the stocks till smax
and you sell it at the price of smax
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numOfTestCase = sc.nextInt();
for (int i = 0; i < numOfTestCase; i++) {
int n = sc.nextInt();
long profit = 0;
int[] stockPrice = new int[n];
for (int j = 0; j < n; j++) {
stockPrice[j] = sc.nextInt();
}
int currMax = Integer.MIN_VALUE;
for (int j = n - 1; j >= 0; j--) {
if (currMax < stockPrice[j]) {
currMax = stockPrice[j];
}
profit += (currMax - stockPrice[j]);
}
System.out.println(profit);
}
}