Maximum number of people that can be killed with strength P | Helper function which returns the sum of series ( 1 ^ 2 + 2 ^ 2 + ... + n ^ 2 ) ; maxPeople function which returns appropriate value using Binary Search in O ( logn ) ; Set the lower and higher values ; Calculate the mid using low and high ; Compare value with n ; Return the ans ; Driver code
function squareSeries ( n ) { return Math . floor ( ( n * ( n + 1 ) * ( 2 * n + 1 ) ) / 6 ) ; } function maxPeople ( n ) { let low = 0 ; let high = 1000000 ; let ans = 0 ; while ( low <= high ) { let mid = low + Math . floor ( ( high - low ) / 2 ) ; let value = squareSeries ( mid ) ; if ( value <= n ) { ans = mid ; low = mid + 1 ; } else { high = mid - 1 ; } } return ans ; } let p = 14 ; document . write ( maxPeople ( p ) ) ;