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.
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}")