LeetCode 2951: Find the Peaks Solution
Master LeetCode problem 2951 (Find the Peaks), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2951. Find the Peaks
Problem Explanation
Explanation:
To find the peaks in the mountain array, we iterate through the array checking each element against its neighbors. If an element is strictly greater than both its neighbors, it is a peak. We need to skip the first and last elements as they cannot be peaks.
Algorithm:
- Iterate through the mountain array from index 1 to n-2.
- For each element at index i, check if mountain[i] > mountain[i-1] and mountain[i] > mountain[i+1].
- If the above condition is true, add the index i to the list of peaks.
- Return the list of peak indices.
Time Complexity: O(n) where n is the number of elements in the mountain array. Space Complexity: O(1) excluding the space for the output list of peak indices.
:
Solution Code
class Solution {
public List<Integer> findPeaks(int[] mountain) {
List<Integer> peaks = new ArrayList<>();
for (int i = 1; i < mountain.length - 1; i++) {
if (mountain[i] > mountain[i - 1] && mountain[i] > mountain[i + 1]) {
peaks.add(i);
}
}
return peaks;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2951 (Find the Peaks)?
This page provides optimized solutions for LeetCode problem 2951 (Find the Peaks) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2951 (Find the Peaks)?
The time complexity for LeetCode 2951 (Find the Peaks) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2951 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2951 in Java, C++, or Python.