-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2391.收集垃圾的最少总时间.js
50 lines (46 loc) · 1.07 KB
/
2391.收集垃圾的最少总时间.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
* @lc app=leetcode.cn id=2391 lang=javascript
*
* [2391] 收集垃圾的最少总时间
*/
// @lc code=start
/**
* @param {string[]} garbage
* @param {number[]} travel
* @return {number}
*/
var garbageCollection = function (garbage, travel) {
let res = 0;
let hasG = false,
hasM = false,
hasP = false;
// 从后向前
// 按字母判断 车需要走到哪里
for (let i = garbage.length - 1; i >= 0; i--) {
let item = garbage[i];
if (item.includes("M") && !hasM) {
res += sum(travel, i);
hasM = true;
}
if (item.includes("P") && !hasP) {
res += sum(travel, i);
hasP = true;
}
if (item.includes("G") && !hasG) {
res += sum(travel, i);
hasG = true;
}
}
return res + garbage.join("").length; // 最后加上所有垃圾的处理时间
};
var sum = function (travel, index) {
let count = 0;
for (let i = 0; i < index; i++) {
count += travel[i];
}
return count;
};
const garbage = ["MMM", "PGM", "GP"],
travel = [3, 10];
console.log(garbageCollection(garbage, travel));
// @lc code=end