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;
        
    }
相关推荐
wenyq73 小时前
LeetCode 2460. Apply Operations to an Array
算法·leetcode
.格子衫.3 小时前
032动态规划之区间DP——算法备赛
算法·动态规划
不会代码的小猴4 小时前
7. JSON
开发语言·c++·笔记·qt·算法·json
怪奇云呼军5 小时前
知识库也会注入指令?闪电智能VoiceAgent 如何防住 Prompt Injection
人工智能·python·算法·云计算·音视频
阿里云大数据AI技术5 小时前
基于 EMR Serverless Ray 实现 Qwen 模型批量推理实践
人工智能·算法·agent
Rambo.xia6 小时前
为什么去马赛克算法,决定了ISP的画质上限
算法·接口隔离原则
Benny_Tang6 小时前
题解:P10230 [COCI 2023/2024 #4] Lepeze
c++·算法
Geek-Chow6 小时前
06 训练管线:数据如何变成权重
人工智能·算法
我变成萤火虫7 小时前
反悔贪心(经典题目讲解)
c++·算法·贪心算法·stl·排序算法·反悔贪心