-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuestion8-longest array mountain
36 lines (26 loc) · 1.16 KB
/
Question8-longest array mountain
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
Given an array arr[] with N elements, the task is to find out the longest sub-array which has the shape of a mountain.
The Longest Peak consists of elements that are initially in ascending order until a peak element is reached and beyond the peak element all other elements of the sub-array are in decreasing order.
Input: arr = [2, 2, 2]
Output: 0
Explanation:
No sub-array exists that shows the behaviour of a mountain sub-array.
Input: arr = [1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5]
Output: 11
def LongestPeak(A):
N = len(A)
result = base = 0
while base < N:
end = base
if end + 1 < N and A[end] < A[end + 1]:
while end+1 < N and A[end] < A[end+1]:
end += 1
if end + 1 < N and A[end] > A[end + 1]:
while end+1 < N and A[end] > A[end+1]:
end += 1
result = max(result, end - base + 1)
base = max(end, base + 1)
return result
if __name__ == "__main__":
d = [ 1, 3, 1, 4, 5, 6,
7, 8, 9, 8, 7, 6, 5 ]
print(LongestPeak(d))