Leetcode-day28-贪心算法

加油站

暴力解法

```

```

贪心算法

贪心的思路是:curSum也就是当前剩余的油量如果小于0了,说明只能从i+1开始走。如果totalSum最终小于0,怎么走都无解。而且题目中说如果是有解,唯一解

复制代码
class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int curSum = 0;
        int totalSum = 0;
        int start = 0;
        for(int i=0;i<cost.length;i++){
            curSum += gas[i] - cost[i];
            totalSum += gas[i] - cost[i];
            if(curSum<0){
                start = i+1;
                curSum=0;
            }
        }
        if(totalSum<0){
        return -1;}
        return start;
        
    }
相关推荐
LYFlied8 小时前
【每日算法】LeetCode 153. 寻找旋转排序数组中的最小值
数据结构·算法·leetcode·面试·职场和发展
唐装鼠8 小时前
rust自动调用Deref(deepseek)
开发语言·算法·rust
ytttr8739 小时前
MATLAB基于LDA的人脸识别算法实现(ORL数据库)
数据库·算法·matlab
jianfeng_zhu11 小时前
整数数组匹配
数据结构·c++·算法
smj2302_7968265211 小时前
解决leetcode第3782题交替删除操作后最后剩下的整数
python·算法·leetcode
LYFlied12 小时前
【每日算法】LeetCode 136. 只出现一次的数字
前端·算法·leetcode·面试·职场和发展
唯唯qwe-12 小时前
Day23:动态规划 | 爬楼梯,不同路径,拆分
算法·leetcode·动态规划
做科研的周师兄13 小时前
中国土壤有机质数据集
人工智能·算法·机器学习·分类·数据挖掘
来深圳13 小时前
leetcode 739. 每日温度
java·算法·leetcode
yaoh.wang13 小时前
力扣(LeetCode) 104: 二叉树的最大深度 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽