Sponsored
Sponsored
The goal is to calculate the minimum time required for each truck to collect all the garbage of its type. A key observation is that the truck only needs to travel as far as the last house that has a specific kind of garbage. We use a prefix sum approach to calculate travel times efficiently. Each truck collects the garbage as it travels to each house that contains its type of garbage.
Time Complexity: O(n * m) where n is the number of houses and m is the average number of garbage types per house.
Space Complexity: O(1) aside from the input storage.
1import java.util.List;
2
3public class GarbageCollection {
4 public int minTimeToCollectGarbage(List<String> garbage, List<Integer> travel) {
5 int[] last = new int[256];
6 int[] prefixSum = new int[travel.size() + 1];
7
8 for (int i = 1; i <= travel.size(); i++) {
9 prefixSum[i] = prefixSum[i - 1] + travel.get(i - 1);
10 }
11
12 int totalTime = 0;
13
14 for (int i = 0; i < garbage.size(); i++) {
15 for (char g : garbage.get(i).toCharArray()) {
16 totalTime++;
17 last[g] = i;
18 }
19 }
20
21 for (char g : new char[]{'M', 'P', 'G'}) {
22 totalTime += prefixSum[last[g]];
23 }
24
25 return totalTime;
26 }
27
28 public static void main(String[] args) {
29 List<String> garbage = List.of("G", "P", "GP", "GG");
30 List<Integer> travel = List.of(2, 4, 3);
31 GarbageCollection gc = new GarbageCollection();
32 System.out.println(gc.minTimeToCollectGarbage(garbage, travel)); // Output: 21
33 }
34}
In Java, the same prefix sum logic is employed to store accumulated travel times. The loop structure is straightforward, iterating over each garbage type, counting the garbage, and updating the last occurrence of each type. This allows calculating the travel time efficiently.
Instead of combining the travel times, here we individually compute the travel needed for each garbage type truck. This method essentially iterates through the garbage list and sums up the necessary travel times and garbage pickup times separately for 'M', 'P', and 'G'. Once that's done, the total represents the minimum time required.
Time Complexity: O(n * m) for each separate call, leading to overall O(3 * n * m).
Space Complexity: O(1) aside from input size.
In the Java solution, we isolate the calculation of each garbage type, leveraging methods like charArray conversion for processing. This enables an assessment of the number of garbage types and the requisite travel additions up to the last point of interest.