Minimum Amount of Time to Collect Garbage

medium array string prefix sum

Problem

Houses contain garbage of types M, P, G. Each truck (one per type) drives from house 0 and stops at the last house with that garbage; travel between houses i and i+1 takes travel[i]. Total time = total chars + sum of travel needed by each truck.

Inputgarbage = ["G","P","GP","GG"], travel = [2,4,3]
Output21
Chars: 1+1+2+2=6. Trucks travel: G→3 reaches 0..3 (cost 9), P→2 (cost 6), M none. 6+9+6=21.

def garbage_collection(garbage, travel):
    n = len(garbage)
    prefix = [0] * n
    for i in range(1, n):
        prefix[i] = prefix[i - 1] + travel[i - 1]
    last = {'M': 0, 'P': 0, 'G': 0}
    total_chars = 0
    for i, g in enumerate(garbage):
        total_chars += len(g)
        for c in g:
            last[c] = i
    return total_chars + prefix[last['M']] + prefix[last['P']] + prefix[last['G']]
function garbageCollection(garbage, travel) {
  const n = garbage.length;
  const prefix = new Array(n).fill(0);
  for (let i = 1; i < n; i++) prefix[i] = prefix[i - 1] + travel[i - 1];
  const last = { M: 0, P: 0, G: 0 };
  let total = 0;
  for (let i = 0; i < n; i++) {
    total += garbage[i].length;
    for (const c of garbage[i]) last[c] = i;
  }
  return total + prefix[last.M] + prefix[last.P] + prefix[last.G];
}
class Solution {
    public int garbageCollection(String[] garbage, int[] travel) {
        int n = garbage.length;
        int[] prefix = new int[n];
        for (int i = 1; i < n; i++) prefix[i] = prefix[i - 1] + travel[i - 1];
        int lm = 0, lp = 0, lg = 0, total = 0;
        for (int i = 0; i < n; i++) {
            total += garbage[i].length();
            for (char c : garbage[i].toCharArray()) {
                if (c == 'M') lm = i;
                else if (c == 'P') lp = i;
                else lg = i;
            }
        }
        return total + prefix[lm] + prefix[lp] + prefix[lg];
    }
}
int garbageCollection(vector<string>& garbage, vector<int>& travel) {
    int n = garbage.size();
    vector<int> prefix(n, 0);
    for (int i = 1; i < n; i++) prefix[i] = prefix[i - 1] + travel[i - 1];
    int lm = 0, lp = 0, lg = 0, total = 0;
    for (int i = 0; i < n; i++) {
        total += (int)garbage[i].size();
        for (char c : garbage[i]) {
            if (c == 'M') lm = i;
            else if (c == 'P') lp = i;
            else lg = i;
        }
    }
    return total + prefix[lm] + prefix[lp] + prefix[lg];
}
Time: O(n + total chars) Space: O(n)