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;
        
    }
相关推荐
语戚16 分钟前
力扣 968. 监控二叉树 —— 贪心 & 树形 DP 双解法递归 + 非递归全解(Java 实现)
java·算法·leetcode·贪心算法·动态规划·力扣·
skywalker_1119 分钟前
力扣hot100-7(接雨水),8(无重复字符的最长子串)
算法·leetcode·职场和发展
bIo7lyA8v1 小时前
算法稳定性分析中的输入扰动建模的技术9
算法
CoderCodingNo2 小时前
【GESP】C++三级真题 luogu-B4499, [GESP202603 三级] 二进制回文串
数据结构·c++·算法
sinat_286945192 小时前
AI Coding 时代的 TDD:从理念到工程落地
人工智能·深度学习·算法·tdd
炽烈小老头2 小时前
【 每天学习一点算法 2026/04/12】x 的平方根
学习·算法
ASKED_20192 小时前
从排序到生成:腾讯广告算法大赛 2025 baseline解读
人工智能·算法
田梓燊2 小时前
leetcode 160
算法·leetcode·职场和发展
_深海凉_2 小时前
LeetCode热题100-颜色分类
python·算法·leetcode