Skip to content

Commit ef3fc20

Browse files
committed
adding longest_peak in python
1 parent 9fd50ea commit ef3fc20

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Arrays/longest_peak.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
Write a function that takes in an array of integers and returns the length of the longest peak
3+
in the array.A peak is defined as adjacent integers in the array that are strictly increasing
4+
until they reach a tip (the highest value in the peak), at which point they become strictly
5+
decreasing. At least three integers are required to form a peak.
6+
"""
7+
8+
9+
10+
#approach
11+
"""
12+
1. iterate through the array from index 1 to len(arr) - 1
13+
2. check if the current element is a peak
14+
3. if it is a peak, then find the length of the peak
15+
4. go to the uphill start
16+
5. go to the downhill end
17+
6. update the ans
18+
"""
19+
20+
arr=[1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3]
21+
22+
23+
def longestPeak(arr: list) -> int:
24+
ans = 0
25+
# iterate through the array from index 1 to len(arr) - 1
26+
for indx in range(1, len(arr) - 1):
27+
# check if the current element is a peak
28+
if arr[indx - 1] < arr[indx] > arr[indx + 1]:
29+
# if it is a peak, then find the length of the peak
30+
uphill_start = downhill_ends = indx
31+
# go to the uphill start
32+
while uphill_start > 0 and arr[uphill_start] > arr[uphill_start - 1]:
33+
uphill_start -= 1
34+
# go to the downhill end
35+
while downhill_ends + 1 < len(arr) and arr[downhill_ends] > arr[downhill_ends + 1]:
36+
downhill_ends += 1
37+
# update the ans
38+
ans = max(ans, (downhill_ends - uphill_start + 1))
39+
return ans
40+
41+
42+
print(longestPeak(arr))
43+
# output: 6

0 commit comments

Comments
 (0)