Skip to content

Instantly share code, notes, and snippets.

@devm33
Created August 3, 2019 17:58
Show Gist options
  • Save devm33/05c80f99ed8600ac218116fbafe0ace9 to your computer and use it in GitHub Desktop.
Save devm33/05c80f99ed8600ac218116fbafe0ace9 to your computer and use it in GitHub Desktop.
package main
import "fmt"
func main() {
a := []int{1, 2, 3, 3, 2, 4, 2}
fmt.Printf("Local max of %v are %v\n", a, localMax(a))
}
func localMax(a []int) []int {
if len(a) <= 1 {
return a
}
r := []int{}
// Special cases for start and end
if a[0] > a[1] {
r = append(r, a[0])
}
if a[len(a)-1] > a[len(a)-2] {
r = append(r, a[0])
}
// O(n) loop to reduce plateaus
for i := 0; i < len(a)-1; i++ {
if a[i] == a[i+1] {
// reslice a to remove
a = append(a[:i], a[i+1:]...)
}
}
// O(n) loop to find local maxima
for i, v := range a {
if i == 0 || i == len(a)-1 {
continue
}
if v > a[i-1] && v > a[i+1] {
r = append(r, v)
}
}
return r
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment