Add other solution for find pick along the array

This commit is contained in:
2024-05-20 16:15:37 -06:00
parent f8534fff74
commit 8d951dd0e6
4 changed files with 178 additions and 0 deletions

33
findPeak.go Normal file
View File

@@ -0,0 +1,33 @@
package main
import "fmt"
// FindPeak finds the peak element in the array
func findPeak(arr []int) int {
n := len(arr)
// first or last element is peak element
if n == 1 {
return 0
}
if arr[0] >= arr[1] {
return 0
}
if arr[n-1] >= arr[n-2] {
return n - 1
}
// check for ever other element
for i := 1; i < n-1; i++ {
// check if the neighbors are smaller
if arr[i] >= arr[i-1] && arr[i] >= arr[i+1] {
return i
}
}
return -1 // inficating no peak found
}
func main() {
arr := []int{1, 3, 20, 4, 1, 21, 0}
fmt.Println("Index of a peak point is", findPeak(arr))
}