Maximize the maximum among minimum of K consecutive sub-arrays in C++

C++Server Side ProgrammingProgramming

Given the task is to divide an array arr[] into K consecutive sub-arrays and find the maximum possible value of maximum among the minimum of the K consecutive sub-srrays.

Input 

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

Output 

9

Explanation − The 3 consecutive sub arrays that can made are: {2, 8, 4, 3}, {9}, and {1, 5}

The minimum values out of all these arrays are: (2, 9, 1)

The maximum value out of these three is 9.

Input 

arr[] = { 8, 4, 1, 9, 11}, K=1

Output 

11

Approach used in the below program as follows

  • If we look at the task, it can be divided into 3 cases − when K=1, k=2 and k>=3.

  • Case 1 − K=1

    When k=1 the sub-array is equal to the array itself and so the minimum value in the array will be the output.

  • Case 2 − K=2

    This is a tough case. In this case we will have to make two arrays that will contain the prefix and suffix minimums as the array can only be divided into 2 parts. Then for every element of the array we will have to do so −

    MaxValue = max(MaxValue, max(prefix minimum value at i, suffix maximum value at i+1))

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
/* Function to find the maximum possible value
of the maximum of minimum of K sub-arrays*/
int Max(const int* arr, int size, int K){
   dint Max;
   int Min;
   //Obtain maximum and minimum
   for (int i = 0; i < size; i++){
      Min = min(Min, arr[i]);
      Max = max(Max, arr[i]);
   }
   //When K=1, return minimum value
   if (K == 1){
      return Min;
   }
   //When K>=3, return maximum value
   else if (K >= 3){
      return Max;
   }
   /*When K=2 then make prefix and suffix minimums*/
   else{
      // Arrays to store prefix and suffix minimums
      int Left[size], Right[size];
      Left[0] = arr[0];
      Right[size - 1] = arr[size - 1];
      // Prefix minimum
      for (int i = 1; i < size; i++){
         Left[i] = min(Left[i - 1], arr[i]);
      }
      // Suffix minimum
      for (int i = size - 2; i >= 0; i--){
         Right[i] = min(Right[i + 1], arr[i]);
      }
      int MaxValue=INT_MIN;
      // Get the maximum possible value
      for (int i = 0; i < size - 1; i++){
         MaxValue = max(MaxValue, max(Left[i], Right[i + 1]));
      }
      return MaxValue;
   }
}
int main(){
   int arr[] = {9,4,12,5,6,11};
   int size = sizeof(arr) / sizeof(arr[0]);
   int K = 2;
   cout<<"Maximize the maximum among minimum of K consecutive sub-arrays is: "<<Max(arr, size, K);
   return 0;
}

Output

If we run the above code we will get the following output −

Maximize the maximum among minimum of K consecutive sub-arrays is: 11
raja
Published on 14-Aug-2020 07:30:23
Advertisements