if (nums == null  nums.length == 0) {
return 0;
}
Stack<Integer> stack = new Stack<Integer>();
int flag = 1;
int res = 1;
stack.push(nums[0]);
for (int i = 1; i < nums.length; i++) {
if (nums[i] <= stack.peek() && flag == 1) {
stack.pop();
stack.push(nums[i]);
}
else if (nums[i] >= stack.peek() && flag == 1) {
stack.pop();
stack.push(nums[i]);
}
else if (nums[i] > stack.peek() && flag == 1) {
stack.push(nums[i]);
flag = 1;
res = Math.max(res, stack.size());
}
else if (nums[i] < stack.peek() && flag == 1) {
stack.push(nums[i]);
flag = 1;
res = Math.max(res, stack.size());
}
}
stack.clear();
flag = 1;
stack.push(nums[0]);
for (int i = 1; i < nums.length; i++) {
if (nums[i] <= stack.peek() && flag == 1) {
stack.pop();
stack.push(nums[i]);
}
else if (nums[i] >= stack.peek() && flag == 1) {
stack.pop();
stack.push(nums[i]);
}
else if (nums[i] > stack.peek() && flag == 1) {
stack.push(nums[i]);
flag = 1;
res = Math.max(res, stack.size());
}
else if (nums[i] < stack.peek() && flag == 1) {
stack.push(nums[i]);
flag = 1;
res = Math.max(res, stack.size());
}
}
return res;
}
Java O(n) solution using stack easy to understand


@willcomeback there is a lot of redundancy in the code. If you pay attention you can reduce the code length.

@agave you are right. This is the first draft I code I think it is much easier to follow.