-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathlongestPeak.go
48 lines (40 loc) · 1.04 KB
/
longestPeak.go
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
package main
import (
"math"
)
func LongestPeak(array []int) int {
if len(array) <= 2 { // we need at least 3 element to form a peak
return 0
}
longestPeakSoFar := 0.0
for currentIdx := 1; currentIdx < len(array)-1; currentIdx++ {
leftIdx := currentIdx // to calculate the left end of the mountain
rightIdx := currentIdx // to calculate the right end of the mountain
isPeak := false
if array[leftIdx-1] < array[currentIdx] && array[rightIdx+1] < array[currentIdx] {
isPeak = true
}
if !isPeak {
continue
}
for leftIdx > 0 {
if array[leftIdx-1] >= array[leftIdx] {
break
}
leftIdx -= 1
}
for rightIdx < len(array)-1 {
if array[rightIdx] <= array[rightIdx+1] {
break
}
rightIdx += 1
}
// ignore half peak mountain
if leftIdx == currentIdx || rightIdx == currentIdx {
continue
}
// to calculate the length end of the mountain
longestPeakSoFar = math.Max(longestPeakSoFar, float64((rightIdx-leftIdx)+1))
}
return int(longestPeakSoFar)
}