Longest Mountain in Array in C++


Consider any (contiguous) subarray B (of A) a called mountain if the following properties hold −

  • size of B >= 3
  • There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]

Suppose we have an array A of integers; we have to find the length of the longest mountain. We have to return 0 if there is no mountain. So if the input is like [2,1,4,7,3,2,5], then the result will be 5. So the largest mountain will be [1,4,7,3,2], whose length is 5.

To solve this, we will follow these steps −

  • ret := 0, n := size of array a
  • i := 0 to n – 1, increase i by j + 1
    • j := i
    • down := false, up := false
    • while j + 1 < n and a[j + 1] > a[j]
      • up := true and increase j by 1
    • while up is true and j + 1 < n and a[j + 1] > a[j]
      • down := true and increase j by 1
    • if up and down both are true, set ret := max of j – i + 1 and ret, decrease j by 1
  • return ret.

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int longestMountain(vector<int>& a) {
      int ret = 0;
      int n = a.size();
      int j;
      for(int i = 0; i < n; i = j + 1){
         j = i;
         bool down = false;
         bool up = false;
         while(j + 1 < n && a[j + 1] > a[j]) {
            up = true;
            j++;
         }
         while(up && j + 1 < n && a[j + 1] < a[j]){
            down = true;
            j++;
         }
         if(up && down){
            ret = max(j - i + 1, ret);
            j--;
         }
      }
      return ret;
   }
};
main(){
   vector<int> v = {2,1,4,7,3,2,5};
   Solution ob;
   cout << (ob.longestMountain(v));
}

Input

[2,1,4,7,3,2,5]

Output

5

Updated on: 05-May-2020

386 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements