Kmspico Download | Official KMS Activator Website [New Version 2024] Fast and Easy Converter YouTube to MP3 Online KMSAuto Net Activator Download 2024 Immediate Byte Pro Neoprofit AI Blacksprut without borders. Discover new shopping opportunities here where each link is an entrance to a world ruled by anonymity and freedom.

How to Find Peak Element in the Array in Go?

Hello Friends Today, through this tutorial, I will tell you How to Find Peak Element in the Array in Go Language Program?

In an array, a peak element is an element that is greater than or equal to its neighbors. Here’s a simple way to find a peak element in an array using the Go programming language:

package main

import "fmt"

func findPeakElement(nums []int) int {
n := len(nums)

// Handle edge cases
if n == 0 {
return -1 // No peak element in an empty array
}

// Check the first and last elements separately
if nums[0] >= nums[1] {
return 0
}
if nums[n-1] >= nums[n-2] {
return n - 1
}

// Iterate through the array to find the peak element
for i := 1; i < n-1; i++ {
if nums[i] >= nums[i-1] && nums[i] >= nums[i+1] {
return i
}
}
return -1 // No peak element found
}
func main() {
// Example usage
arr := []int{1, 3, 20, 4, 1, 0}
result := findPeakElement(arr)
if result != -1 {
fmt.Printf("Peak element found at index %d with value %d\n", result, arr[result])
} else {
fmt.Println("No peak element found in the array.")
}
}

In this example, the `findPeakElement` function takes an array as input and returns the index of a peak element. The function checks the first and last elements separately, and then iterates through the array to find a peak element by comparing each element with its neighbors. The `main` function provides an example of how to use the `findPeakElement` function.