Maximum size of sub-array that satisfies the given condition in C++ program


In this problem, we are given an array arr[] of n integers. Our task is to create a program to find the maximum size of sub-array that satisfies the given condition.

Problem Description − We need to find the length of largest subarray that satisfies any one of the below condition,

  • arr[k] > arr[k+1], if k is odd and arr[k] < arr[k+1], if k is even. For all elements of the subarray.

  • arr[k] < arr[k+1], if k is odd and arr[k] > arr[k+1], if k is even. For all elements of the subarray.

Here, k is the index of the element of the subarray in arr[].

Let’s take an example to understand the problem,

Input

arr[] = {7, 3, 1, 5, 4, 2, 9}

Output

4

Explanation

The subarray {3, 1, 5, 4} satisfies the condition 1.
k = 1(odd), arr[k] > arr[k+1], 3 > 1
k = 2(even), arr[k] < arr[k+1], 1 < 5
k = 3(odd), arr[k] > arr[k+1], 5 > 4

Solution Approach

We can see from the example that for any of the conditions to be true. The subarray should have alternate greater-smaller elements i.e. if 1st > 2nd, then 2nd > 3rd, and so on.

Now, for ease of calculation, we will create a relation array indicating this relationship. The following is how we will be tailoring the relation array,

If arr[i] == arr[i + 1],relArr[i] = ‘E’
If arr[i] > arr[i + 1],relArr[i] = ‘G’
If arr[i] < arr[i + 1],relArr[i] = ‘S’

Using this array we can easily find the max subarray size. Subarray to be considered will have alternate ‘G’ and ‘S’.

Example

Program to illustrate the working of our solution,

 Live Demo

#include<iostream>
using namespace std;
char findRel(int a, int b) {
   if(a > b)
      return 'G';
   else if(a < b)
      return 'S';
   return 'E';
}
int calcMaxSubArray(int arr[], int n) {
   int maxLen = 1;
   int len = 1;
   char c = findRel(arr[0], arr[1]);
   for(int i = 1; i <= n−1; i++){
      if(c == 'S' && findRel(arr[i], arr[i + 1]) == 'G')
         len++;
      else if(c == 'G' && findRel(arr[i], arr[i + 1]) == 'S')
         len++;
      else {
         if(maxLen < (len + 1))
            maxLen = (len + 1);
         len = 1;
      }
      c = findRel(arr[i], arr[i+1]);
   }
   return maxLen;
}
int main() {
   int arr[] = {7, 3, 1, 5, 4, 2, 9};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The maximum size of sub−array that satisfies the given
   condition is "<<calcMaxSubArray(arr, n);
}

Output

The maximum size of sub-array that satisfies the given condition is 4

Updated on: 09-Dec-2020

97 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements