Skip to content

Commit 43cd23b

Browse files
authored
Merge pull request #1122 from vandit98/first_repeat_python
adding longest_peak in python
2 parents da627c8 + 50af8cf commit 43cd23b

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Arrays/longest_peak.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
# Time Complexity: O(n)
20+
# Space Complexity: O(1)
21+
22+
23+
24+
arr=[1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3]
25+
26+
27+
def longestPeak(arr: list) -> int:
28+
ans = 0
29+
# iterate through the array from index 1 to len(arr) - 1
30+
for indx in range(1, len(arr) - 1):
31+
# check if the current element is a peak
32+
if arr[indx - 1] < arr[indx] > arr[indx + 1]:
33+
# if it is a peak, then find the length of the peak
34+
uphill_start = downhill_ends = indx
35+
# go to the uphill start
36+
while uphill_start > 0 and arr[uphill_start] > arr[uphill_start - 1]:
37+
uphill_start -= 1
38+
# go to the downhill end
39+
while downhill_ends + 1 < len(arr) and arr[downhill_ends] > arr[downhill_ends + 1]:
40+
downhill_ends += 1
41+
# update the ans
42+
ans = max(ans, (downhill_ends - uphill_start + 1))
43+
return ans
44+
45+
46+
print(longestPeak(arr))
47+
# output: 6

0 commit comments

Comments
 (0)