Longest Mountain Subarray
Last Updated :
12 Jul, 2025
Given an array arr[] with N elements, the task is to find out the longest sub-array which has the shape of a mountain.
Note: A mountain sub-array starts with an increasing sequence, reaches a peak, and then follows a decreasing sequence.
Examples:
Input: arr = [2, 2, 2]
Output: 0
Explanation: No sub-array exists that shows the behavior of a mountain sub-array.
Input: arr = [1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5]
Output: 11
Explanation: Longest sub-array Mountain [1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5] which have length 11
[Naive Approach] Using the Nested loops - O(N^2) Time and O(1) Space
We can solve this problem using nested loops: the outer loop iterates over the array, while the inner loop finds the mountain length starting at the outer loop's index. The inner loop first checks the increasing slope, then the decreasing slope. If both exist, we update the maximum mountain length accordingly.
C++
#include <bits/stdc++.h>
using namespace std;
int LongestMountain(vector<int> &a)
{
int ans = 0;
int n = a.size();
// iterate over the array
for (int i = 0; i < n; i++)
{
int j = i + 1;
int inc = 0, dec = 0;
// check weather it make it is increase first or not
while (j < n && a[j] > a[j - 1])
{
inc = 1;
j++;
}
// check weather it is decreasing after checking the increaseing part
while (j < n && a[j] < a[j - 1])
{
dec = 1;
j++;
}
// if mountain
if (inc && dec)
{
ans = max(j - i, ans);
inc = 0, dec = 0;
}
}
// return maximum length
return ans;
}
int main()
{
vector<int> d = {1, 3, 1, 4,
5, 6, 7, 8,
9, 8, 7, 6, 5};
cout << LongestMountain(d)
<< endl;
return 0;
}
Java
import java.util.*;
public class GfG {
public static int findLongestMountain(int[] a) {
int ans = 0;
int n = a.length;
// Iterate over the array
for (int i = 0; i < n; i++) {
int j = i + 1;
int inc = 0, dec = 0;
// Check increasing sequence
while (j < n && a[j] > a[j - 1]) {
inc = 1;
j++;
}
// Check decreasing sequence
while (j < n && a[j] < a[j - 1]) {
dec = 1;
j++;
}
// If a mountain is found, update max length
if (inc == 1 && dec == 1) {
ans = Math.max(ans, j - i);
}
}
return ans;
}
public static void main(String[] args) {
int[] d = {1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5};
System.out.println(findLongestMountain(d));
}
}
Python
def longest_mountain(a):
ans = 0
n = len(a)
# Iterate over the array
for i in range(n):
j = i + 1
inc, dec = 0, 0
# Check increasing sequence
while j < n and a[j] > a[j - 1]:
inc = 1
j += 1
# Check decreasing sequence
while j < n and a[j] < a[j - 1]:
dec = 1
j += 1
# If a mountain is found, update max length
if inc and dec:
ans = max(ans, j - i)
return ans
# Driver code
d = [1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5]
print(longest_mountain(d))
C#
using System;
using System.Collections.Generic;
class GfG
{
static int LongestMountain(List<int> a)
{
int ans = 0; // Store the answer
int n = a.Count;
// Iterate over the array
for (int i = 0; i < n; i++)
{
int j = i + 1;
int inc = 0, dec = 0;
// Check if it's increasing first
while (j < n && a[j] > a[j - 1])
{
inc = 1;
j++;
}
// Check if it's decreasing after increasing
while (j < n && a[j] < a[j - 1])
{
dec = 1;
j++;
}
// If it's a valid mountain
if (inc == 1 && dec == 1)
{
ans = Math.Max(j - i, ans);
}
}
return ans;
}
static void Main()
{
List<int> d = new List<int> { 1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5 };
Console.WriteLine(LongestMountain(d));
}
}
JavaScript
function LongestMountain(arr) {
let ans = 0; // Store the answer
let n = arr.length;
// Iterate over the array
for (let i = 0; i < n; i++) {
let j = i + 1;
let inc = 0, dec = 0;
// Check if it's increasing first
while (j < n && arr[j] > arr[j - 1]) {
inc = 1;
j++;
}
// Check if it's decreasing after increasing
while (j < n && arr[j] < arr[j - 1]) {
dec = 1;
j++;
}
// If it's a valid mountain
if (inc && dec) {
ans = Math.max(j - i, ans);
}
}
return ans;
}
// Driver Code
let d = [1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5];
console.log(LongestMountain(d));
[Expected Approach] Peak Expansion Strategy - O(N) Time and O(1) Space
Use the two-pointer approach to find the longest mountain subarray efficiently. Traverse the array to identify peak elements (arr[i-1] < arr[i] > arr[i+1]
). For each peak, expand outward with two pointers: move left while elements increase and right while they decrease. Update the maximum length accordingly and continue traversal. Return the longest recorded mountain length.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the
// longest mountain subarray
int LongestMountain(vector<int> &arr)
{
int n = arr.size();
if (n < 3)
return 0;
int ans = 0;
for (int i = 1; i <= n - 2;)
{
if (arr[i] > arr[i - 1] and arr[i] > arr[i + 1])
{
int count = 0;
int j = i;
while (arr[j] > arr[j - 1] and j > 0)
count++, j--;
while (arr[i] > arr[i + 1] and i <= n - 2)
count++, i++;
ans = max(ans, count);
}
else
i++;
}
if (ans > 0)
return ans + 1;
return ans;
}
// Driver code
int main()
{
vector<int> d = {1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5};
cout << LongestMountain(d) << endl;
return 0;
}
Java
import java.util.ArrayList;
public class GfG {
// Function to find the
// longest mountain subarray
public static int
LongestMountain(ArrayList<Integer> arr)
{
int n = arr.size();
if (n < 3) // base condition for having the mountain
return 0;
int ans = 0;
for (int i = 1; i <= n - 2;) {
if (arr.get(i) > arr.get(i - 1)
&& arr.get(i) > arr.get(i + 1)) {
int count = 0;
// now we find the index where a peak is
// present
int j = i;
while (j > 0
&& arr.get(j) > arr.get(j - 1)) {
count++;
j--;
}
while (i <= n - 2
&& arr.get(i) > arr.get(i + 1)) {
count++;
i++;
}
ans = Math.max(ans, count);
}
else {
i++;
}
}
if (ans > 0)
return ans + 1;
return ans;
}
// Driver code
public static void main(String[] args)
{
ArrayList<Integer> d = new ArrayList<>();
d.add(1);
d.add(3);
d.add(1);
d.add(4);
d.add(5);
d.add(6);
d.add(7);
d.add(8);
d.add(9);
d.add(8);
d.add(7);
d.add(6);
d.add(5);
System.out.println(LongestMountain(d));
}
}
Python
import math
def LongestMountain(arr):
n = len(arr)
if n < 3: # base condition for having the mountain
return 0
ans = 0
i = 1
while i <= n - 2:
if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]:
count = 0
# now we find the index where a peak is present
j = i
while j > 0 and arr[j] > arr[j - 1]:
count += 1
j -= 1
while i <= n - 2 and arr[i] > arr[i + 1]:
count += 1
i += 1
ans = max(ans, count)
else:
i += 1
if ans > 0:
return ans + 1
return ans
# Driver code
d = [1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5]
print(LongestMountain(d))
C#
using System;
public class GfG {
public static int LongestMountain(int[] arr)
{
int n = arr.Length;
if (n < 3) { // base condition for having the mountain
return 0;
}
int ans = 0;
int i = 1;
while (i <= n - 2) {
if (arr[i] > arr[i - 1]
&& arr[i] > arr[i + 1]) {
int count = 0;
// now we find the index where a peak is
// present
int j = i;
while (j > 0 && arr[j] > arr[j - 1]) {
count += 1;
j -= 1;
}
while (i <= n - 2 && arr[i] > arr[i + 1]) {
count += 1;
i += 1;
}
ans = Math.Max(ans, count);
}
else {
i += 1;
}
}
if (ans > 0) {
return ans + 1;
}
return ans;
}
public static void Main()
{
int[] d = { 1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5 };
Console.WriteLine(LongestMountain(d));
}
}
JavaScript
function LongestMountain(arr)
{
// define the length of the array
let n = arr.length;
// base condition for having the mountain
if (n < 3) {
return 0;
}
// set the ans to 0
let ans = 0;
// set i to 1
let i = 1;
// while loop
while (i <= n - 2) {
// if statement to check if element at i is greater
// than element at i-1 and i+1
if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) {
// set count to 0
let count = 0;
// now we find the index where a peak is present
let j = i;
while (j > 0 && arr[j] > arr[j - 1]) {
// increment count
count++;
// decrement j
j--;
}
// while loop to check if i is less than or
// equal to n - 2 and element at i is greater
// than element at i+1
while (i <= n - 2 && arr[i] > arr[i + 1]) {
// increment count
count++;
// increment i
i++;
}
// set ans to the maximum value of ans and count
ans = Math.max(ans, count);
}
else {
// increment i
i++;
}
}
// if statement to check if ans is greater than 0
if (ans > 0) {
// return ans + 1
return ans + 1;
}
// return ans
return ans;
}
let output = LongestMountain(
[ 1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5 ]);
// log the output
console.log(output);
[Alternate Approach] Using two Pointers - O(n) Time and O(1) Space
Use the two-pointer approach to find the longest mountain subarray. Set j
(start of increase) and k
(end of decrease) as -1
. Traverse the array, setting j
at the start of an increasing slope and updating k
when a decreasing slope follows. If both are valid, update the maximum mountain length. Reset j
and k
if a flat region appears, and return the longest recorded mountain length.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the
// longest mountain subarray
int LongestMountain(vector<int> &a)
{
int i = 0, j = -1, k = -1, p = 0, d = 0, n = 0;
// cann't make the mountain
if (a.size() < 3)
{
return 0;
}
for (i = 0; i < a.size() - 1; i++)
{
if (a[i + 1] > a[i])
{
if (k != -1)
{
k = -1;
j = -1;
}
// Set the value of j to current index i.
if (j == -1)
{
j = i;
}
}
else
{
// Checks if next element is
// less than current element
if (a[i + 1] < a[i])
{
// if the starting element
// of the mountain sub-array exists
// then the index of ending element
// is stored in k
if (j != -1)
{
k = i + 1;
}
// if mountain take maximum
if (k != -1 && j != -1)
{
if (d < k - j + 1)
{
d = k - j + 1;
}
}
}
else
{
k = -1;
j = -1;
}
}
}
// if mountain take maximum
if (k != -1 && j != -1)
{
if (d < k - j + 1)
{
d = k - j + 1;
}
}
return d;
}
int main()
{
vector<int> d = {1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5};
cout << LongestMountain(d) << endl;
return 0;
}
Java
import java.io.*;
class GFG {
public static int LongestMountain(int a[])
{
int i = 0, j = -1, k = -1, d = 0;
// cann't mountain
if (a.length < 3)
return 0;
for (i = 0; i < a.length - 1; i++) {
if (a[i + 1] > a[i]) {
if (k != -1) {
k = -1;
j = -1;
}
if (j == -1)
j = i;
}
else {
// Checks if next element is
// less than current element
if (a[i + 1] < a[i]) {
if (j != -1)
k = i + 1;
// if mountain make update d
if (k != -1 && j != -1) {
if (d < k - j + 1)
d = k - j + 1;
}
}
else {
k = -1;
j = -1;
}
}
}
if (k != -1 && j != -1) {
if (d < k - j + 1)
d = k - j + 1;
}
return d;
}
public static void main(String[] args)
{
int a[] = { 1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5 };
System.out.println(LongestMountain(a));
}
}
Python
# Function to find the
# longest mountain subarray
def LongestMountain(a):
i = 0
j = -1
k = -1
p = 0
d = 0
n = 0
if (len(a) < 3):
return 0
for i in range(len(a) - 1):
if (a[i + 1] > a[i]):
# reset it
if (k != -1):
k = -1
j = -1
# value of j to current index i.
if (j == -1):
j = i
else:
# Checks if next element is
# less than current element
if (a[i + 1] < a[i]):
if (j != -1):
k = i + 1
# if mountain update answer
if (k != -1 and j != -1):
if (d < k - j + 1):
d = k - j + 1
else:
k = -1
j = -1
if (k != -1 and j != -1):
if (d < k - j + 1):
d = k - j + 1
return d
d = [1, 3, 1, 4, 5, 6,
7, 8, 9, 8, 7, 6, 5]
print(LongestMountain(d))
C#
using System;
class GfG {
public static int LongestMountain(int[] a)
{
int i = 0, j = -1, k = -1, d = 0;
// cann't make the mountain
if (a.Length < 3)
return 0;
for (i = 0; i < a.Length - 1; i++) {
if (a[i + 1] > a[i]) {
if (k != -1) {
k = -1;
j = -1;
}
if (j == -1)
j = i;
}
else {
if (a[i + 1] < a[i]) {
if (j != -1)
k = i + 1;
// update the answer if mountain
if (k != -1 && j != -1) {
if (d < k - j + 1)
d = k - j + 1;
}
}
// reset the value of the k and j
else {
k = -1;
j = -1;
}
}
}
// update the value of d if mountain
if (k != -1 && j != -1) {
if (d < k - j + 1)
d = k - j + 1;
}
return d;
}
public static void Main(String[] args)
{
int[] a = { 1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5 };
Console.WriteLine(LongestMountain(a));
}
}
JavaScript
function LongestMountain(a)
{
let i = 0, j = -1, k = -1, p = 0, d = 0, n = 0;
// cann't about the make the mountain
if (a.length < 3)
return 0;
for (i = 0; i < a.length - 1; i++) {
if (a[i + 1] > a[i]) {
// reset the value of k and j
if (k != -1) {
k = -1;
j = -1;
}
// value of j to current index i.
if (j == -1)
j = i;
}
else {
// Checks if next element is
// less than current element
if (a[i + 1] < a[i]) {
if (j != -1)
k = i + 1;
// if mountain update answer
if (k != -1 && j != -1) {
if (d < k - j + 1)
d = k - j + 1;
}
}
else {
k = -1;
j = -1;
}
}
}
// check the mountain accordingly update the answer
if (k != -1 && j != -1) {
if (d < k - j + 1)
d = k - j + 1;
}
return d;
}
let a = [ 1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5 ];
console.log(LongestMountain(a));
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem