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.

Cialis (Tadalafil) är den främsta konkurrenten till Viagra (Sildenafil) på marknaden för erektil dysfunktion. köpa Cialis i Sverige föredras av många på grund av sin längre varaktighet och anses vara det mest kostnadseffektiva varumärkesbaserade ED-läkemedlet som finns tillgängligt i Sverige. Cialis finns i två varianter: Cialis och Cialis Daily, och fyra olika doseringar: 2,5 mg, 5 mg, 10 mg och 20 mg, erbjuder Cialis också en rad olika alternativ för att passa patientens behov.