Minimise the maximum element of N subarrays of size K | C ++ implementation to choose N subarrays of size K such that the maximum element of subarrays is minimum ; Function to choose N subarrays of size K such that the maximum element of subarrays is minimum ; Condition to check if it is not possible to choose k sized N subarrays ; Using binary search ; calculating mid ; Loop to find the count of the K sized subarrays possible with elements less than mid ; Condition to check if the answer is in right subarray ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minDays ( vector < int > & arr , int n , int k ) { int l = arr . size ( ) , left = 1 , right = 1e9 ; if ( n * k > l ) return -1 ; while ( left < right ) { int mid = ( left + right ) / 2 , cnt = 0 , product = 0 ; for ( int j = 0 ; j < l ; ++ j ) { if ( arr [ j ] > mid ) { cnt = 0 ; } else if ( ++ cnt >= k ) { product ++ ; cnt = 0 ; } } if ( product < n ) { left = mid + 1 ; } else { right = mid ; } } return left ; } int main ( ) { vector < int > arr { 1 , 10 , 3 , 10 , 2 } ; int n = 3 , k = 1 ; cout << minDays ( arr , n , k ) << endl ; return 0 ; }