Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find stone removal rate in K hours in Python
Suppose we have a list of numbers called piles and a value k. The piles[i] represents the number of stones on 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] and k = 5, then the output will be 3. For r = 3 stones per hour, we can clear the second pile in 2 hours (6÷3=2), the third pile in 2 hours (4÷3=2, rounded up), and the first pile in 1 hour (3÷3=1), totaling 5 hours.
Algorithm
We use binary search to find the minimum stone removal rate ?
- Set
l = 1(minimum possible rate) - Set
h = max(piles)(maximum possible rate needed) - For each candidate rate, calculate total hours needed using ceiling division
- Use binary search to find the minimum rate that works within
khours
Implementation
from math import ceil
def solve(piles, k):
l = 1
h = max(piles)
def turns(r):
return sum(ceil(pile / r) for pile in piles)
while l < h:
mid = (l + h) // 2
if turns(mid) > k:
l = mid + 1
else:
h = mid
return l
# Test the function
piles = [3, 6, 4]
k = 5
result = solve(piles, k)
print(f"Minimum stone removal rate: {result}")
Minimum stone removal rate: 3
How It Works
The algorithm uses binary search on the answer space. For each candidate removal rate mid, we calculate how many hours it would take to clear all piles ?
from math import ceil
def demonstrate_calculation(piles, rate):
total_hours = 0
print(f"For removal rate {rate}:")
for i, pile in enumerate(piles):
hours_needed = ceil(pile / rate)
total_hours += hours_needed
print(f" Pile {i+1} ({pile} stones): {hours_needed} hours")
print(f" Total hours: {total_hours}")
return total_hours
piles = [3, 6, 4]
demonstrate_calculation(piles, 3)
print()
demonstrate_calculation(piles, 2)
For removal rate 3: Pile 1 (3 stones): 1 hours Pile 2 (6 stones): 2 hours Pile 3 (4 stones): 2 hours Total hours: 5 For removal rate 2: Pile 1 (3 stones): 2 hours Pile 2 (6 stones): 3 hours Pile 3 (4 stones): 2 hours Total hours: 7
Key Points
- Binary search range: 1 to max(piles)
- Use ceiling division to calculate hours per pile
- If total hours > k, increase the removal rate
- If total hours ? k, try a smaller removal rate
Conclusion
This solution uses binary search to efficiently find the minimum stone removal rate. The time complexity is O(n log m) where n is the number of piles and m is the maximum pile size.
