public int[] buildMaxTree(int[] A, int n) {
// write code here
if (A == null || n < 1) {
return null;
}
Stack<Integer> findStack = new Stack<Integer>();
Integer[] leftMax = new Integer[n];
Integer[] rightMax = new Integer[n];
for (int i = 0; i < n; i++) {
while (!findStack.empty() && A[findStack.peek()] <= A[i]) {
findStack.pop();
}
if (findStack.empty())
leftMax[i] = null;
else
leftMax[i] = findStack.peek();
findStack.push(new Integer(i));
}
while (!findStack.empty()) {
findStack.pop();
}
for (int i = n - 1; i >= 0; i--) {
while (!findStack.empty() && A[findStack.peek()] <= A[i]) {
findStack.pop();
}
if (findStack.empty())
rightMax[i] = null;
else
rightMax[i] = findStack.peek();
findStack.push(new Integer(i));
}
int[] res = new int[n];
int j = 0;
for (int i = 0; i < n; ++i) {
if (leftMax[i] != null && rightMax[i] != null) {
if (A[leftMax[i]] < A[rightMax[i]])
res[j++] = leftMax[i];
else
res[j++] = rightMax[i];
}
else if (leftMax[i] != null && rightMax[i] == null) {
res[j++] = leftMax[i];
}
else if (leftMax[i] == null && rightMax[i] != null) {
res[j++] = rightMax[i];
}
else {
res[j++] = -1;
}
}
return res;
}