Leetcode 845: Longest Mountain in Array

grid47
grid47
Exploring patterns and algorithms
Aug 14, 2024 7 min read

Given an integer array arr, you need to find the length of the longest subarray that forms a mountain. A mountain subarray has the following properties: it must have at least three elements, the elements strictly increase to a peak, and then strictly decrease after the peak. If no such subarray exists, return 0.
Problem
Approach
Steps
Complexity
Input: You are given an integer array `arr` containing non-negative integers.
Example: Input: arr = [1, 3, 2, 4, 7, 5, 3]
Constraints:
• 1 <= arr.length <= 10^4
• 0 <= arr[i] <= 10^4
Output: Return the length of the longest mountain subarray. If no valid mountain exists, return 0.
Example: Output: 5
Constraints:
• The array must have at least 3 elements to form a valid mountain.
Goal: The goal is to find the longest subarray in the form of a mountain. A peak must be surrounded by strictly increasing and strictly decreasing elements.
Steps:
• Step 1: Traverse through the array and calculate the length of the subarray before and after each peak.
• Step 2: For each peak, calculate how far the elements on the left strictly increase and how far the elements on the right strictly decrease.
• Step 3: Keep track of the longest mountain found and return its length.
Goal: The solution should handle arrays with lengths up to 10^4 efficiently, ensuring that the peak and its surroundings strictly increase and decrease.
Steps:
• The array must contain at least 3 elements to form a mountain.
• There should be a peak element where arr[i-1] < arr[i] > arr[i+1].
Assumptions:
• The array is not empty and contains valid integers.
• The array elements are non-negative.
Input: Input: [1, 3, 2, 4, 7, 5, 3]
Explanation: The longest mountain is [3, 2, 4, 7, 5], which has length 5.

Input: Input: [1, 2, 3, 4]
Explanation: There is no mountain because the array only increases.

Input: Input: [8, 7, 6, 5]
Explanation: There is no mountain because the array only decreases.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus