human
Value to be subtracted from array elements to make sum of all elements equals K | Function to return the amount of wood collected if the cut is made at height m.
Function that returns Height at which cut should be made.
Sort the heights of the trees.
The minimum and the maximum cut that can be made.
Binary search to find the answer.
The amount of wood collected when cut is made at the mid.
If the current collected wood is equal to the required amount.
If it is more than the required amount then the cut needs to be made at a height higher than the current height.
Else made the cut at a lower height.
Driver code"
How can the above be solved in Python?
assistant
#Here is code to value to be subtracted from array elements to make sum of all elements equals K and the other steps required.
 def woodCollected ( height , n , m ) :
	sum = 0
	for i in range ( n - 1 , - 1 , - 1 ) :
		if ( height [ i ] - m <= 0 ) :
			break
		sum += ( height [ i ] - m )
	return sum
def collectKWood ( height , n , k ) :
	height = sorted ( height )
	low = 0
	high = height [ n - 1 ]
	while ( low <= high ) :
		mid = low + ( ( high - low ) // 2 )
		collected = woodCollected ( height , n , mid )
		if ( collected == k ) :
			return mid
		if ( collected > k ) :
			low = mid + 1
		else :
			high = mid - 1
	return - 1
height = [ 1 , 2 , 1 , 2 ]
n = len ( height )
k = 2
print ( collectKWood ( height , n , k ) )