Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Maximum length of mountain in an array using JavaScript
A mountain subsequence in JavaScript is a contiguous subarray that first increases then decreases, forming a mountain-like pattern. This article explains how to find the maximum length of such a subsequence.
Mountain Subsequence Definition
A subarray is considered a mountain if it meets these criteria:
Length ? 3 elements
Elements strictly increase to a peak, then strictly decrease
Pattern: sub[0] sub[i+1] > ... > sub[n-1]
Problem Statement
Given an array of numbers, find the length of the longest mountain subsequence. Return 0 if no valid mountain exists.
Example Input:
const arr = [3, 2, 5, 8, 4, 3, 6];
Expected Output:
5
Explanation: The mountain [2, 5, 8, 4, 3] has length 5.
Solution
const arr = [3, 2, 5, 8, 4, 3, 6];
const mountainLength = (arr = []) => {
let max = 0;
for (let left = 0; left < arr.length; left++) {
let right = left;
// Find ascending part
while (right < arr.length - 1 && arr[right] < arr[right + 1]) {
right++;
}
const peak = right;
// Find descending part
while (right < arr.length - 1 && arr[right] > arr[right + 1]) {
right++;
}
// Valid mountain: has both ascending and descending parts
if (right > peak && peak > left) {
max = Math.max(max, right - left + 1);
left = right - 1; // Skip processed elements
}
}
return max;
};
console.log(mountainLength(arr));
5
How It Works
The algorithm uses a two-pointer approach:
Find ascending sequence: Move right pointer while elements increase
Mark peak: Store the highest point of the mountain
Find descending sequence: Continue moving right while elements decrease
Validate mountain: Ensure both ascending and descending parts exist
Update maximum: Track the longest valid mountain found
Additional Example
const testCases = [
[1, 2, 3, 2, 1], // Perfect mountain
[1, 2, 3, 4, 5], // Only ascending
[5, 4, 3, 2, 1], // Only descending
[1, 3, 5, 4, 2, 6, 8, 7, 3, 1] // Multiple mountains
];
testCases.forEach((test, index) => {
console.log(`Test ${index + 1}: [${test}] ? ${mountainLength(test)}`);
});
Test 1: [1,2,3,2,1] ? 5 Test 2: [1,2,3,4,5] ? 0 Test 3: [5,4,3,2,1] ? 0 Test 4: [1,3,5,4,2,6,8,7,3,1] ? 6
Time Complexity
The algorithm runs in O(n) time complexity where n is the array length. Each element is visited at most twice during the scanning process.
Conclusion
Finding the maximum mountain length requires identifying contiguous subarrays with strict ascending-then-descending patterns. The two-pointer technique efficiently scans the array once to find all valid mountains.
