845. Longest Mountain in Array
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
maxLen
to 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
maxLen
if 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.
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;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.