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?
For example, if you know that prices for the next two days are prices=[1,2], you should buy one share day one, and sell it day two for a profit of 1. If they are instead [2,1], no profit can be made so you don't buy or sell stock those days.
Sample Input
3
3
5 3 2
3
1 2 100
4
1 3 1 2
Sample Output
0
197
3
My code is:
static int stockmax(int[] prices) {
int temp[][]=new int[prices.length][prices.length];
int max;
int sum=0;
for(int i=0;i<prices.length;i++)
{
max=0;
for(int j=0;j<prices.length;j++)
{
if(j<=i)
{
temp[i][j]=0;
}
else{
temp[i][j]=prices[j]-prices[i];
}
if(temp[i][j]>max)
max=temp[i][j];
}
sum+=max;
}
return sum;
}
I am getting the wrong answer to this question. Can anyone say why is this code wrong?