```
public class Solution {
public int maxProfit(int[] prices) {
int length=prices.length;
int []max=new int[length];
int []min=new int[length];
int minnum=Integer.MAX_VALUE,maxnum=Integer.MIN_VALUE,result;
for(int i=0;i<length-1;i++)
{
if(prices[i]<minnum){
minnum=prices[i];
}
min[i]=minnum;
}
for(int i=length-2;i>=0;i--)
{
if(prices[i+1]>maxnum){
maxnum=prices[i+1];
}
max[i]=maxnum;
}
result=0;
for(int i=0;i<length-1;i++)
{
if(max[i]-min[i]>result)
result=max[i]-min[i];
}
return result;
}
}
```