Skip to content

Commit 94be5de

Browse files
author
Tushar Roy
committed
Find largest mountain in the array
1 parent 7ef2d31 commit 94be5de

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.interview.array;
2+
3+
/**
4+
* https://leetcode.com/problems/longest-mountain-in-array/description/
5+
*/
6+
public class LargestMountain {
7+
8+
public int longestMountain(int[] nums) {
9+
int start = 0;
10+
int max = 0;
11+
State state = State.STARTED;
12+
for (int i = 1; i < nums.length; i++) {
13+
if (nums[i] == nums[i - 1]) {
14+
start = i;
15+
state = State.STARTED;
16+
}
17+
else if (nums[i] > nums[i - 1]) {
18+
if (state == State.DECREASING || state == State.STARTED) {
19+
start = i - 1;
20+
state = State.INCREASING;
21+
}
22+
} else {
23+
if (state == State.INCREASING || state == State.DECREASING) {
24+
state = State.DECREASING;
25+
max = Math.max(max, i - start + 1);
26+
} else {
27+
start = i;
28+
}
29+
}
30+
}
31+
return max;
32+
}
33+
34+
enum State {
35+
STARTED,
36+
INCREASING,
37+
DECREASING;
38+
}
39+
40+
public static void main(String[] args) {
41+
LargestMountain lm = new LargestMountain();
42+
int[] nums = {2, 1, 4, 7, 3, 2, 5};
43+
System.out.println(lm.longestMountain(nums));
44+
}
45+
}

0 commit comments

Comments
 (0)