Divide an array into k segments to maximize maximum of segment minimums

link 0

Given an array of n integers, divide it into k segments and find the maximum of the minimums of k segments. Output the maximum integer that can be obtained among all ways to segment in k subarrays.


Input : arr[] = {1, 2, 3, 6, 5}  
        k = 2
Output: 5
Explanation: There are many ways to create 
two segments. The optimal segments are (1, 2, 3)
and (6, 5). Minimum of both segments are 1 and 5, 
hence the maximum(1, 5) is 5. 

Input: -4 -5 -3 -2 -1 k=1
Output: -5 
Explanation: only one segment, so minimum is -5.

There will be 3 cases that need to be considered.

  1. k >= 3: When k is greater then 2, one segment will only compose of {max element}, so that max of minimum segments will always be the max.
  2. k = 2: For k = 2 the answer is the maximum of the first and last element.
  3. k = 1: Only possible partition is one segment equal to the whole array. So the answer is the minimum value on the whole array.

Below is the c++ implementation of the above approach

// CPP Program to find maximum value of
// maximum of minimums of k segments.
#include <bits/stdc++.h>
using namespace std;

// function to calculate the max of all the
// minimum segments
int maxOfSegmentMins(int a[], int n, int k)
    // if we have to divide it into 1 segment
    // then the min will be the answer
    if (k == 1) 
       return *min_element(a, a+n);

    if (k == 2) 
       return max(a[0], a[n-1]);  
    // If k >= 3, return maximum of all
    // elements.
    return *max_element(a, a+n);

// driver program to test the above function
int main()
    int a[] = { -10, -9, -8, 2, 7, -6, -5 };
    int n = sizeof(a) / sizeof(a[0]);
    int k = 2;
    cout << maxOfSegmentMins(a, n, k);



Time complexity: O(n)
Auxiliary Space: O(1)

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits: http://www.geeksforgeeks.org
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements


Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar