-
Notifications
You must be signed in to change notification settings - Fork 5
/
LongestMountainInArray.java
69 lines (64 loc) · 1.88 KB
/
LongestMountainInArray.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*https://leetcode.com/problems/longest-mountain-in-array/*/
class Solution {
public int longestMountain(int[] arr) {
int n = arr.length;
int[] left = new int[n], right = new int[n];
for (int i = 1; i < n; ++i)
if (arr[i] > arr[i-1])
left[i] = left[i-1]+1;
for (int i = n-2; i >= 0; --i)
if (arr[i] > arr[i+1])
right[i] = right[i+1]+1;
int max = 0;
for (int i = 1; i < n-1; ++i)
if (left[i]+right[i]+1 > max && left[i] != 0 && right[i] != 0)
max = left[i]+right[i]+1;
return max;
}
}
class Solution {
public int longestMountain(int[] arr) {
int n = arr.length;
int[] right = new int[n];
for (int i = n-2; i >= 0; --i)
if (arr[i] > arr[i+1])
right[i] = right[i+1]+1;
int max = 0, curr = 0;
for (int i = 1; i < n-1; ++i)
{
if (arr[i] > arr[i-1])
++curr;
else curr = 0;
if (curr+right[i]+1 > max && curr != 0 && right[i] != 0)
max = curr+right[i]+1;
}
return max;
}
}
class Solution {
public int longestMountain(int[] arr) {
int ans=0;
for(int i=0;i<arr.length-2;i++){
int count=0;
if(arr[i]<arr[i+1] && arr[i+1]>arr[i+2]){
int j=i+1;
while(j>=1 && arr[j]>arr[j-1] ){
count++;
j--;
}
j=i+1;
while(j<arr.length-1 && arr[j]>arr[j+1] ) {
count++;
j++;
}
if(count>ans&& count!=0){
ans=count;
}
}
}
if(ans==0){
return 0;
}
return ans+1;
}
}