【算法心得】minus instead of add

https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/description/?envType=daily-question&envId=2023-11-20

Here is my code:
【算法心得】minus instead of add_第1张图片

function garbageCollection(garbage: string[], travel: number[]): number {
    const arr=['M','P','G'];
    let tmptime=0;
    let ans=0;
    for(let c=0;c<3;c++){
        tmptime=0;
        for(let i=0;i<garbage.length;i++){
            if(!i) tmptime+=0;
            else tmptime+=travel[i-1];
            let cnt=garbage[i].split(arr[c]).length-1;
            if(cnt){
                tmptime+=cnt;
                ans+=tmptime;
                tmptime=0;
            }
        }
    }
    return ans;
};

I cant believe that, only 9%

https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/solutions/4307686/beats-100-explained-with-video-modified-sum-visualized-too/?envType=daily-question&envId=2023-11-20
The solution is quite smart, This question can be reverted to what to minus instead of what to add, that is, after one type of garbage is cleaned up, no need to move forward anymore. What about time to clean? calculating each time garbage trunk to clean up garbage is very slow, but we only need to know the sum of these time, it is the total word length of garbage[].

From now on I will try to write blog in English, there may be a lot of grammar issue in these articles, but I think I am only a learner, it is a part of study.

你可能感兴趣的:(算法,算法)