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;
        
    }
相关推荐
Darkwanderor7 小时前
什么数据量适合用什么算法
c++·算法
zc.ovo8 小时前
河北师范大学2026校赛题解(A,E,I)
c++·算法
py有趣8 小时前
力扣热门100题之环形链表
算法·leetcode·链表
py有趣8 小时前
力扣热门100题之回文链表
算法·leetcode·链表
月落归舟10 小时前
帮你从算法的角度来认识二叉树---(二)
算法·二叉树
SilentSlot11 小时前
【数据结构】Hash
数据结构·算法·哈希算法
样例过了就是过了12 小时前
LeetCode热题100 柱状图中最大的矩形
数据结构·c++·算法·leetcode
wsoz12 小时前
Leetcode哈希-day1
算法·leetcode·哈希算法
阿Y加油吧12 小时前
LeetCode 二叉搜索树双神题通关!有序数组转平衡 BST + 验证 BST,小白递归一把梭
java·算法·leetcode