Depending on your actual requirement you can make another trade off.
At the storage cost of 1 Integer object, you can get your max value with complexity O(1) without sorting, with O(1) cost for PUSH and with O(n) cost when popping elements from stack.
public class IntStackWithMax {
private Integer maxVal = Integer.MIN_VALUE;
private Vector<Integer> values = new Vector<Integer>();
// cost O(1)
public Integer getMaxVal() {
return maxVal;
}
//cost O(1)
public boolean push(Integer item) {
maxVal = Math.max(maxVal, item);
return values.add(item);
}
//cost O(n) (!!!)
public Integer pop() {
Integer result = values.remove(values.size() - 1);
maxVal = Collections.max(values);
return result;
}
//cost O(1)
public Integer peek() {
return values.lastElement();
}
}
Please also note that this is NOT thread safe.