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;
        
    }
相关推荐
crescent_悦15 分钟前
PTA L1-020 帅到没朋友 C++
数据结构·c++·算法
鳄鱼儿39 分钟前
密码算法的OID查阅
算法
lxh01131 小时前
螺旋数组题解
前端·算法·js
czlczl200209252 小时前
算法:二叉树的公共祖先
算法
小白程序员成长日记3 小时前
2025.11.23 力扣每日一题
算法·leetcode·职场和发展
16_one4 小时前
autoDL安装Open-WebUi+Rag本地知识库问答+Function Calling
人工智能·后端·算法
散峰而望5 小时前
C++数组(三)(算法竞赛)
开发语言·c++·算法·github
q***95225 小时前
SpringMVC 请求参数接收
前端·javascript·算法
初级炼丹师(爱说实话版)5 小时前
多进程与多线程的优缺点及适用场景总结
算法
hetao17338375 小时前
2025-11-25~26 hetao1733837的刷题记录
c++·算法