Blog

Problem Statement: Find the Mountain Peak

Description:

You are given a sequence of distinct integers that initially increases and then decreases, representing the heights of a mountain range. This sequence forms a “mountain” due to its strictly increasing and then strictly decreasing nature. Your task is to find the peak of the mountain, i.e., the highest value in the sequence.

Gaming Laptop

Objective:

Write a function that takes this sequence of integers as input and returns the value of the peak element.

Constraints:

  • The input list will have at least three numbers.
  • The sequence represents a mountain, which means it will strictly increase to a point (the peak) and then strictly decrease.
  • The peak is guaranteed to be unique.

Example:

Input: [2, 5, 8, 12, 15, 20, 25, 30, 28, 24, 18, 10, 5, 1]
Output: 30

Explanation:

The sequence increases from 2 to 30 and then decreases from 30 to 1. Thus, the peak of this mountain is 30.

  • Java
  • Python
public class MountainPeakFinder {
    public static int findPeak(int[] arr) {
        int low = 0, high = arr.length - 1;
        
        while (low < high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] < arr[mid + 1]) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }
        return arr[low];
    }

    public static void main(String[] args) {
        int[] arr = {2, 5, 8, 12, 15, 20, 25, 30, 28, 24, 18, 10, 5, 1};
        int peak = findPeak(arr);
        System.out.println("The peak is: " + peak);
    }
}
def find_peak(arr):
    low, high = 0, len(arr) - 1
    
    while low < high:
        mid = (low + high) // 2
        if arr[mid] < arr[mid + 1]:
            low = mid + 1
        else:
            high = mid
    return arr[low]

# Example usage
arr = [2, 5, 8, 12, 15, 20, 25, 30, 28, 24, 18, 10, 5, 1]
peak = find_peak(arr)
print(f"The peak is: {peak}")

Avatar

Neelabh

About Author

As Neelabh Singh, I am a Senior Software Engineer with 6.6 years of experience, specializing in Java technologies, Microservices, AWS, Algorithms, and Data Structures. I am also a technology blogger and an active participant in several online coding communities.

You may also like

Blog Design Pattern

Understanding the Builder Design Pattern in Java | Creational Design Patterns | CodeTechSummit

Overview The Builder design pattern is a creational pattern used to construct a complex object step by step. It separates
Blog Tech Toolkit

Base64 Decode

Base64 encoding is a technique used to encode binary data into ASCII characters, making it easier to transmit data over