Find whether a subarray is in form of a mountain or not in C++


In this problem, we are given an array of integers arr[] and an range. Our task is to find whether a subarray is in the form of a mountain or not.

Let's take an example to understand the problem,

Input : arr[] = {1, 4, 2, 5, 6, 7, 3, 0}, range = [2, 7]
Output : Yes

Explanation

Subarray of range = {2, 5, 6, 7, 3, 0}
The values first increase and then decrease.

Solution Approach

A simple solution to the problem is by using extra arrays. We will find the index of the last element which is increasing for each element of the array and do the same for decreasing values. Then check for the mountain in the given range of time.

Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
int processArray(int arr[], int N, int left[], int right[]){
   left[0] = 0;
   int increasingValR = 0;
   for (int i = 1; i < N; i++){
      if (arr[i] > arr[i - 1])
         increasingValR = i;
      left[i] = increasingValR;
   }
   right[N - 1] = N - 1;
   int decreasingValL = N - 1;
   for (int i = N - 2; i >= 0; i--){
      if (arr[i] > arr[i + 1])
         decreasingValL = i;
      right[i] = decreasingValL;
   }
}
bool isMountainSubArray(int arr[], int left[], int right[], int L, int R){
   return (right[L] >= left[R]);
}
int main(){
   int arr[] = {2, 3, 2, 4, 4, 6, 3, 2};
   int N = sizeof(arr) / sizeof(int);
   int left[N], right[N];
   processArray(arr, N, left, right);
   int L = 0;
   int R = 2;
   if (isMountainSubArray(arr, left, right, L, R))
      cout<<"The subarray is in mountain form";
   else
      cout<<"The subarray is not in mountain form";
   return 0;
}

Output

The subarray is in mountain form

Updated on: 01-Feb-2022

87 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements