【算法心得】minus instead of add

文章讨论了一个编程问题,如何在LeetCode上计算清理不同类型的垃圾所需的最少时间。解决方案是利用字符串分割和优化算法,避免重复计算时间。关键在于理解每次清理后不需要继续前行,只需累计清理每个类型垃圾所需的时间总和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Here is my code:
在这里插入图片描述

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值