2391. Minimum Amount of Time to Collect Garbage
你的城市有一大堆房子
房子裡面有垃圾
垃圾一共分M, P, G三種
你有三台垃圾車分別能撿起M, P, G三種垃圾
垃圾車從0號房子開始
必須依照路線路過房子並撿起垃圾(0=>1=>2=>3)
但是無須經過所有房子
垃圾車每次能撿起一個垃圾
撿起一個垃圾須花費一分鐘
從i號房子走到i+1號房子需花費travel[i]分鐘
當有一台垃圾車運作的時候另外兩台車禁止做任何事情
回傳撿起所有垃圾最小花費的分鐘數
Input: garbage = ["G","P","GP","GG"], travel = [2,4,3]
Output: 21
P垃圾車花費:2(走到1)+1(撿起垃圾)+4(走到2)+1(撿起垃圾)=8
G垃圾車花費:1(撿起垃圾)+2(走到1)+4(走到2)+1(撿起垃圾)+3(走到3)+2(撿起垃圾)=13
總花費:8+13=21
Input: garbage = ["MMM","PGM","GP"], travel = [3,10]
Output: 37
P垃圾車花費:15
G垃圾車花費:15
M垃圾車花費:7
總花費:15+15+7=37
Intuition:
三種垃圾不會互相影響
個別分開算加起來就好
Approach:
如果後面有垃圾
就繼續往後走然後撿起來
所以我們先用一個變數cost記錄他走路花費的時間
然後如果查到有垃圾就加到result
TS Code:
function takeGarbage (garbage: string[], travel: number[], garbageType:
string): number {
let result = 0
let cost = 0
for (let i = 0; i < garbage.length; i++) {
if (garbage[i].includes(garbageType)) {
result += cost
cost = 0
for (let j = 0; j < garbage[i].length; j++) {
if (garbage[i][j] === garbageType) result++
}
}
if (i < travel.length) cost += travel[i]
}
return result
}
function garbageCollection (garbage: string[], travel: number[]): number {
return takeGarbage(garbage, travel, "G") + takeGarbage(garbage, travel,
"P") + takeGarbage(garbage, travel, "M")
}