Split the given array into K sub | C ++ implementation of the above approach ; Function to check if mid can be maximum sub - arrays sum ; If individual element is greater maximum possible sum ; Increase sum of current sub - array ; If the sum is greater than mid increase count ; Check condition ; Function to find maximum subarray sum which is minimum ; int start = * max ; Max subarray sum , considering subarray of length 1 ; end += array [ i ] ; Max subarray sum , considering subarray of length n ; Answer stores possible maximum sub array sum ; If mid is possible solution Put answer = mid ; ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int mid , int array [ ] , int n , int K ) { int count = 0 ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( array [ i ] > mid ) return false ; sum += array [ i ] ; if ( sum > mid ) { count ++ ; sum = array [ i ] ; } } count ++ ; if ( count <= K ) return true ; return false ; } int solve ( int array [ ] , int n , int K ) { int * max = max_element ( array , array + n ) ; int end = 0 ; for ( int i = 0 ; i < n ; i ++ ) { } int answer = 0 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( check ( mid , array , n , K ) ) { answer = mid ; end = mid - 1 ; } else { start = mid + 1 ; } } return answer ; } int main ( ) { int array [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( array ) / sizeof ( array [ 0 ] ) ; int K = 3 ; cout << solve ( array , n , K ) ; }