LeetCode 845: Longest Mountain in Array Solution
Master LeetCode problem 845 (Longest Mountain in Array), a medium 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.
845. Longest Mountain in Array
Problem Explanation
Explanation
To solve this problem, we can iterate through the array and look for potential mountain peaks. Once we find a peak, we can expand to the left and right to find the length of the mountain. We can keep track of the longest mountain found so far and return its length at the end.
- Initialize variables
maxLento 0 to store the length of the longest mountain found so far. - Iterate through the array from index 1 to
arr.length - 2. - Check if the current element is a peak (arr[i] is greater than both its neighbors).
- If it is a peak, expand to the left and right to find the length of the mountain.
- Update
maxLenif the current mountain length is greater thanmaxLen. - Return the final
maxLen.
Time Complexity: O(N) where N is the number of elements in the array. We iterate through the array once. Space Complexity: O(1) as we are using constant extra space.
Solution Code
class Solution {
public int longestMountain(int[] arr) {
int maxLen = 0;
for (int i = 1; i < arr.length - 1; i++) {
if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) {
int left = i - 1;
int right = i + 1;
while (left > 0 && arr[left] > arr[left - 1]) {
left--;
}
while (right < arr.length - 1 && arr[right] > arr[right + 1]) {
right++;
}
maxLen = Math.max(maxLen, right - left + 1);
}
}
return maxLen;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 845 (Longest Mountain in Array)?
This page provides optimized solutions for LeetCode problem 845 (Longest Mountain in Array) 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 845 (Longest Mountain in Array)?
The time complexity for LeetCode 845 (Longest Mountain in Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 845 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 845 in Java, C++, or Python.