当前位置: 首页 > news >正文

LeetCode134☞加油站

关联LeetCode题号134

本题特点
  • 贪心
  • 局部最优解-部分差值 如果小于0(消耗大于油站油量) 就从下一个加油站开始,因为如果中间有小于0的情况 当前站就不可能是始发站,
  • 整体最优解-整体差值 如果小于0 ,那么就是不能有始发站
本题思路
class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        curSum = 0
        totalSum = 0
        start = 0
        
        for i in range(len(gas)):
            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
java写法
package leetcode;

import org.junit.jupiter.api.Test;

/**
 * File Description: gasStation_134
 * Author: Your Name
 * Date: 2024/12/24
 */
public class gasStation_134 {

    public int canCompleteCircuit(int[] gas, int[] cost) {
        int curSum = 0;
        int totalSum = 0;
        int start = 0;
        for (int i = 0; i < gas.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;

    }

    @Test
    public void TestCanCompleteCircuit() {
        int[] gas = {2,3,4};
        int[] cost = {3,4,3};
        int start = canCompleteCircuit(gas, cost);
        System.out.println(start);
    }

}

相关文章:

  • 07-单链表-单链表基本操作
  • 【Pandas】pandas Series cat
  • 【计算机网络】浏览器组成、工作原理、页面渲染流程...
  • 国内首款载重1吨级无人运输机TP1000首飞成功 2026年投入应急救援
  • CAN总线的CC帧和FD帧之间如何仲裁
  • 2025-03-17 NO.1 Quest3 开发环境配置教程
  • 初阶数据结构习题【16】(5二叉树)——965. 单值二叉树
  • langchain如何并行调用运行接口
  • 代码随想录算法训练营第六十五天| 图论10
  • 《Android启动侦探团:追踪Launcher启动的“最后一公里”》
  • 设计模式之抽象工厂模式
  • element plus组件Carousel组件3个卡片平铺样式改造
  • docker nginx
  • A - 整数的简单问题/A - A Simple Problem with Integers
  • 《算法笔记》8.2小节——搜索专题->广度优先搜索(BFS)问题 E: 【宽搜入门】巧妙取量
  • 基于 Prometheus + Grafana 监控微服务和数据库
  • 职业教育五金建设改革解析
  • C# 一文读懂委托与事件
  • Web Component 教程(二):如何有效管理和使用自定义属性
  • ✎ 一次有趣的经历
  • 巴菲特批评贸易保护主义:贸易不该被当成武器来使用
  • 五年来首次!香港金管局斥资465.39亿港元购买美元
  • 世界黄金协会:一季度全球黄金投资需求同比增170%
  • 中国海警位中国黄岩岛领海及周边区域执法巡查
  • 应急管理部派出工作组赴山西太原小区爆炸现场指导救援处置
  • 许峰已任江苏省南京市副市长