# Program to find stone removal rate in K hours in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called piles and a value k. The piles[i] represents, the number of stones on the pile i. On each hour, we select any pile and remove r number of stones from that pile. If we pick a pile with fewer than r stones, it still takes an hour to clear the pile. We have to find the minimum value of r, such that we can remove all the stones in less than or equal to k hours.

So, if the input is like piles = [3, 6, 4] k = 5, then the output will be 3, because, for r = 3 stones per hour, we can clear the second pile in 2 hours, then clear the third in 2 hours, and clear the first pile in 1 hour.

To solve this, we will follow these steps −

• l := 1
• h := maximum of piles
• r := h
• Define a function turns() . This will take r
• return sum of all elements present in the list with (ceiling of b / r for each b in piles)
• From the main method, do the following −
• while l < h, do
• mid := floor of (l + h) / 2
• if turns(mid) > k, then
• l := mid + 1
• otherwise,
• h := mid
• r := minimum of r and mid
• return r

## Example

Let us see the following implementation to get better understanding −

from math import ceil
def solve(piles, k):
l = 1
h = max(piles)
r = h

def turns(r):
return sum(ceil(b / r) for b in piles)
while l < h:
mid = (l + h) // 2
if turns(mid) > k:
l = mid + 1
else:
h = mid
r = min(r, mid)
return r

piles = [3, 6, 4]
k = 5
print(solve(piles, k))

## Input

[3, 6, 4], 5

## Output

3
Published on 18-Oct-2021 12:36:13