LeetCode 2391: Minimum Amount of Time to Collect Garbage

ArrayStringPrefix Sum

Problem Description

Explanation:

To solve this problem, we can simulate the process of each garbage truck picking up their respective garbage. We iterate through each house, calculate the time taken for each type of garbage truck to pick up the garbage at that house, and update the total time taken accordingly. We keep track of the time taken by each type of garbage truck separately and consider the maximum time taken overall.

  1. Iterate through each house:

    • Calculate the time taken by each type of garbage truck to pick up the garbage at that house.
    • Update the total time taken by each type of garbage truck.
    • Consider the maximum time taken among all garbage trucks.
  2. Return the total time taken as the minimum amount of time to collect all garbage.

Time Complexity: O(n), where n is the number of houses. Space Complexity: O(1)

Solutions

class Solution {
    public int minTimeToCollectGarbage(String[] garbage, int[] travel) {
        int metalTime = 0, paperTime = 0, glassTime = 0;
        
        for (int i = 0; i < garbage.length; i++) {
            for (char c : garbage[i].toCharArray()) {
                if (c == 'M') {
                    metalTime += travel[i];
                } else if (c == 'P') {
                    paperTime += travel[i];
                } else if (c == 'G') {
                    glassTime += travel[i];
                }
            }
        }
        
        return Math.max(metalTime, Math.max(paperTime, glassTime));
    }
}

Loading editor...