Welcome to CodeYourCraft, where we learn to code together! Today, we're going to dive into an exciting topic called Find Peak Element. This concept is essential for understanding and solving various problems related to data structures and algorithms. Let's get started!
A peak element in an array is an element that is greater than its neighboring elements on both sides (if such elements exist). In other words, a peak element is the highest point in a mountain range (or array) represented by numbers.
Here's a simple example:
arr = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]In the above array, the peak element is 5, as it's higher than the elements on both sides (assuming we consider the first and last elements as neighbors).
The algorithm to find the peak element is quite straightforward. Let's go through the steps together:
Let's put this algorithm into practice with an example:
def findPeak(arr):
# Initialize the peak index
peak = len(arr) - 1
# Iterate through the array, starting from the second element
for i in range(1, len(arr)):
if arr[i] > arr[peak]:
# If the current element is higher, update the peak index
peak = i
return arr[peak]
arr = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]
print(findPeak(arr)) # Output: 5In this example, we defined a findPeak function that takes an array as an argument and returns the peak element. The function iterates through the array and compares each element with the current peak element. If it finds a higher element, it updates the peak index accordingly.
Let's consider an advanced example where the array may have multiple peaks and we need to find the highest peak:
arr = [2, 1, 2, 3, 4, 7, 10, 9, 8, 7, 6, 5, 4, 3, 2]
def findPeak(arr):
# Initialize the peak index and maximum height
peak = 0
max_height = arr[0]
# Iterate through the array, starting from the second element
for i in range(1, len(arr)):
if arr[i] > max_height:
# If the current element is higher, update the maximum height and peak index
max_height = arr[i]
peak = i
return arr[peak]
print(findPeak(arr)) # Output: 10In this example, we defined a similar findPeak function, but this time we initialize a variable to store the maximum height found so far. This allows us to handle multiple peaks in the array.
What is a peak element in an array?
That's all for today! I hope you found the lesson on finding peak elements interesting and informative. Practice makes perfect, so feel free to try implementing this algorithm on your own or modify it to fit different scenarios. Happy coding! š