Maximize value at Kth index to create N size array with adjacent difference 1 and sum less than M | Function to calculate maximum value that can be placed at the Kth index in a distribution in which difference of adjacent elements is less than 1 and total sum of distribution is M . ; variable to store final answer ; variables for binary search ; Binary search ; variable for binary search ; variable to store total sum of array ; number of indices on the left excluding the Kth index ; number of indices on the left excluding the Kth index ; add mid to final sum ; distribution on left side is possible ; sum of distribution on the left side ; sum of distribution on the left side with ( L - mid ) 1 s ; distribution on right side is possible ; sum of distribution on the right side ; sum of distribution on the left side with ( R - mid ) 1 s ; Distribution is valid ; return answer ; Input ; Function call
function calculateMax ( N , M , K ) { var ans = - 1 ; var low = 0 , high = M ; while ( low <= high ) { var mid = parseInt ( ( low + high ) / 2 ) ; var val = 0 ; var L = K - 1 ; var R = N - K ; val += mid ; if ( mid >= L ) { val += ( L ) * ( ( 2 * mid - L - 1 ) / 2 ) ; } else { val += mid * parseInt ( ( mid - 1 ) / 2 ) + ( L - mid ) ; } if ( mid >= R ) { val += ( R ) * ( 2 * mid - R - 1 ) / 2 ; } else { val += mid * parseInt ( ( mid - 1 ) / 2 ) + ( R - mid ) ; } if ( val <= M ) { ans = Math . max ( ans , mid ) ; low = mid + 1 ; } else high = mid - 1 ; } return ans ; } let N = 7 , M = 100 , K = 6 ; document . write ( calculateMax ( N , M , K ) ) ;