
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements