Open In App

Longest Mountain Subarray

Last Updated : 12 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:
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));

Output
11

[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);

Output
11

[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));

Output
11


Article Tags :

Similar Reads