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;
        
    }
相关推荐
sheeta199819 分钟前
LeetCode 每日一题笔记 日期:2026.06.06 题目:2196. 根据描述创建二叉树
笔记·算法·leetcode
小欣加油26 分钟前
leetcode994 腐烂的橘子
数据结构·c++·算法·leetcode·bfs
QuZero1 小时前
Guava Cache Deep Dive
java·后端·算法·guava
随意起个昵称1 小时前
线性dp-LIS题目4(A Twisty Movement)
算法·动态规划
Felven1 小时前
B. Fair Numbers
数据结构·算法
人道领域2 小时前
【LeetCode刷题日记】93.复原IP地址
java·开发语言·算法·leetcode
jarreyer2 小时前
【算法记录1】模型训练问题
算法
Felven2 小时前
D. Friends and the Restaurant
算法
想吃火锅10052 小时前
【leetcode】165.比较版本号js
javascript·算法·leetcode
San813_LDD2 小时前
[量化]《浮点数比较的艺术:从内存布局到极致性能优化》
网络·算法