[LeetCode] Minimum Amount of Time to Collect Garbage

2391. Minimum Amount of Time to Collect Garbage

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int garbageCollection(vector<string>& garbage, vector<int>& travel) {
int res = 0;
int a = 0, b = 0, c = 0;
vector<int> psum{0};
for(int i = 0; i < garbage.size(); i++) {
if(i != garbage.size() - 1)
psum.push_back(psum.back() + travel[i]);
for(int j = 0; j < garbage[i].length(); j++) {
if(garbage[i][j] == 'M') a = i, res++;
if(garbage[i][j] == 'P') b = i, res++;
if(garbage[i][j] == 'G') c = i, res++;
}
}
res += psum[a];
res += psum[b];
res += psum[c];
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/28/PS/LeetCode/minimum-amount-of-time-to-collect-garbage/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.