Skip to main content
Back to problems
#2391
Medium Algorithms

Minimum amount of time to collect garbage

Array String Prefix Sum
85.1% acceptance
Feb 25, 2026
1630
245
You are given a 0-indexed array of strings garbage where garbage[i] represents the assortment of garbage at the ith house. garbage[i] consists only of the characters 'M', 'P' and 'G' representing one unit of metal, paper and glass garbage respectively. Picking up one unit of any type of garbage takes 1 minute. You are also given a 0-indexed integer array travel where travel[i] is the number of minutes needed to go from house i to house i + 1. There are three garbage trucks in the city, each responsible for picking up one type of garbage. Each garbage truck starts at house 0 and must visit each house in order; however, they do not need to visit every house. Only one garbage truck may be used at any given moment. While one truck is driving or picking up garbage, the other two trucks cannot do anything. Return the minimum number of minutes needed to pick up all the garbage.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn garbage_collection(garbage: Vec<String>, travel: Vec<i32>) -> i32 {
    let n = garbage.len();
    let type_idx = |c: char| -> usize { match c { 'M' => 0, 'P' => 1, _ => 2 } };
    let mut last = [0usize; 3];
    let mut count = [0i32; 3];
    for (i, g) in garbage.iter().enumerate() {
      for c in g.chars() {
        let t = type_idx(c);
        last[t] = i;
        count[t] += 1;
      }
    }
    let mut prefix_travel = vec![0i32; n];
    for i in 1..n { prefix_travel[i] = prefix_travel[i-1] + travel[i-1]; }
    (0..3).map(|t| count[t] + prefix_travel[last[t]]).sum()
  }
}