Split the given array into K sub | 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 ; var 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
function check ( mid , array , n , K ) { var count = 0 ; var sum = 0 ; for ( var 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 ; } function solve ( array , n , K ) { var max = array . reduce ( ( a , b ) => Math . max ( a , b ) ) ; var end = 0 ; for ( var i = 0 ; i < n ; i ++ ) { } var answer = 0 ; while ( start <= end ) { var mid = parseInt ( ( start + end ) / 2 ) ; if ( check ( mid , array , n , K ) ) { answer = mid ; end = mid - 1 ; } else { start = mid + 1 ; } } return answer ; } var array = [ 1 , 2 , 3 , 4 ] ; var n = array . length ; var K = 3 ; document . write ( solve ( array , n , K ) ) ;