# How to Find the Longest Mountain in Array in Java

## The challenge

Let’s call any (contiguous) subarray B (of A) a mountain if the following properties hold:

• `B.length >= 3`
• There exists some `0 < i < B.length - 1` such that `B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]`

(Note that B could be any subarray of A, including the entire array A.)

Given an array `A` of integers, return the length of the longest mountain

Return `0` if there is no mountain.

Example 1:

```Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.```

Example 2:

```Input: [2,2,2]
Output: 0
Explanation: There is no mountain.```

Note:

1. `0 <= A.length <= 10000`
2. `0 <= A[i] <= 10000`

• Can you solve it using only one pass?
• Can you solve it in `O(1)` space?

## The solution in Java code

```.wp-block-code{border:0;padding:0}.wp-block-code>div{overflow:auto}.shcb-language{border:0;clip:rect(1px,1px,1px,1px);-webkit-clip-path:inset(50%);clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-wrap:normal;word-break:normal}.hljs{box-sizing:border-box}.hljs.shcb-code-table{display:table;width:100%}.hljs.shcb-code-table>.shcb-loc{color:inherit;display:table-row;width:100%}.hljs.shcb-code-table .shcb-loc>span{display:table-cell}.wp-block-code code.hljs:not(.shcb-wrap-lines){white-space:pre}.wp-block-code code.hljs.shcb-wrap-lines{white-space:pre-wrap}.hljs.shcb-line-numbers{border-spacing:0;counter-reset:line}.hljs.shcb-line-numbers>.shcb-loc{counter-increment:line}.hljs.shcb-line-numbers .shcb-loc>span{padding-left:.75em}.hljs.shcb-line-numbers .shcb-loc::before{border-right:1px solid #ddd;content:counter(line);display:table-cell;padding:0 .75em;text-align:right;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;white-space:nowrap;width:1%}```class Solution {
public int longestMountain(int[] A) {
int N = A.length;
int answer = 0, base = 0;

while (base < N) {
int end = base;

if (end + 1 < N && A[end] < A[end + 1]) {

while (end + 1 < N && A[end] < A[end + 1]) end++;

if (end + 1 < N && A[end] > A[end + 1]) {
while (end + 1 < N && A[end] > A[end + 1])
end++;
}
}

base = Math.max(end, base + 1);
}