![]() |
VOOZH | about |
Given n machines represented by an integer array arr[], where arr[i] denotes the time (in seconds) taken by the i-th machine to produce one item. All machines work simultaneously and continuously. Additionally, we are also given an integer m, representing the total number of items required. The task is to determine the minimum time needed to produce exactly m items efficiently.
Examples:
Input: arr[] = [2, 4, 5], m = 7
Output: 8
Explanation: The optimal way to produce 7 items in the minimum time is 8 seconds. Each machine produces items at different rates:
- Machine 1 produces an item every 2 seconds → Produces 8/2 = 4 items in 8 seconds.
- Machine 2 produces an item every 4 seconds → Produces 8/4 = 2 items in 8 seconds.
- Machine 3 produces an item every 5 seconds → Produces 8/5 = 1 item in 8 seconds.
Total items produced in 8 seconds = 4 + 2 + 1 = 7
Input: arr[] = [2, 3, 5, 7], m = 10
Output: 9
Explanation: The optimal way to produce 10 items in the minimum time is 9 seconds. Each machine produces items at different rates:
- Machine 1 produces an item every 2 seconds - Produces 9/2 = 4 items in 9 seconds.
- Machine 2 produces an item every 3 seconds - Produces 9/3 = 3 items in 9 seconds.
- Machine 3 produces an item every 5 seconds - Produces 9/5 = 1 item in 9 seconds.
- Machine 4 produces an item every 7 seconds - Produces 9/7 = 1 item in 9 seconds.
Total items produced in 9 seconds = 4 + 3 + 1 + 1 = 10
Table of Content
The idea is to incrementally check the minimum time required to produce exactly m items. We start with time = 1 and keep increasing it until the total items produced by all machines ≥ m. At each time step, we compute the number of items each machine can produce using time / arr[i] and sum them up. Since all machines work simultaneously, this approach ensures we find the smallest valid time.
8
Time Complexity: O(n*m*min(arr)) because for each time unit (up to m * min(arr)), we iterate through n machines to count produced items.
Space Complexity: O(1), as only a few integer variables are used; no extra space is allocated.
The idea is to use Binary Search instead of checking each time sequentially, we observe that the total items produced in a given time T can be computed in O(n). The key observation is that the minimum possible time is 1, and the maximum possible time is m * minMachineTime. By applying binary search on this range, we repeatedly check the mid value to determine if it's sufficient and adjust the search space accordingly.
Steps to implement the above idea:
8
Time Complexity: O(n log(m*min(arr))), as Binary Search runs log(m × min(arr)) times, each checking n machines.
Space Complexity: O(1), as only a few extra variables are used, making it constant space.