Minimum K such that sum of array elements after division by K does not exceed S | Function to return the minimum value of k that satisfies the given condition ; Find the maximum element ; Lowest answer can be 1 and the highest answer can be ( maximum + 1 ) ; Binary search ; Get the mid element ; Calculate the sum after dividing the array by new K which is mid ; Search in the second half ; First half ; Driver code
function findMinimumK ( a , n , s ) { var maximum = a [ 0 ] ; for ( i = 0 ; i < n ; i ++ ) { maximum = Math . max ( maximum , a [ i ] ) ; } var low = 1 , high = maximum + 1 ; var ans = high ; while ( low <= high ) { var mid = parseInt ( ( low + high ) / 2 ) ; var sum = 0 ; for ( i = 0 ; i < n ; i ++ ) { sum += parseInt ( ( a [ i ] / mid ) ) ; } if ( sum > s ) low = mid + 1 ; else { ans = Math . min ( ans , mid ) ; high = mid - 1 ; } } return ans ; } var a = [ 10 , 7 , 8 , 10 , 12 , 19 ] ; var n = a . length ; var s = 27 ; document . write ( findMinimumK ( a , n , s ) ) ;