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;
        
    }
相关推荐
m0_5474866612 分钟前
《智能计算》全套课件PDF(武汉工程大学)
算法·贝叶斯算法·智能计算
weixin_3077791343 分钟前
Jupyter SQL 表血缘分析并导出 Excel
开发语言·python·sql·算法·excel
Lazyafei1 小时前
560. 和为 K 的子数组
数据结构·算法
小白的高手之路1 小时前
【LeetCode 热题 100】240. 搜索二维矩阵 II|矩阵、二分查找、Z 字形查找(Python)
python·算法·leetcode·矩阵·力扣
geovindu1 小时前
python:DBSCAN
开发语言·后端·python·算法
Tim_101 小时前
【LeetCode】 525. 连续数组
算法
小蒋学算法2 小时前
算法-将数据流变为多个不相交区间-TreeMap
算法
Mortalbreeze2 小时前
图论算法篇:A*、Floyd、Bellman-Ford、SPFA
数据结构·c++·算法
Eyfcom10 小时前
〖物流数据安全 02〗差分隐私与同态加密的工程边界:跨境物流快递系统该为隐私付出多少计算代价?
算法·机器学习·同态加密·跨境物流快递系统·物流数据安全