Leetcode Gas Station
来源:互联网 发布:批判性思维工具 知乎 编辑:程序博客网 时间:2024/05/16 15:53
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]
.
You have a car with an unlimited gas tank and it costs cost[i]
of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
Difficulty: Medium
Solution: tricky greedy problem
To solve this problem, we need to understand and use the following 2 facts:
1) if the sum of gas >= the sum of cost, then the circle can be completed.
2) if A can not reach C in a the sequence of A-->B-->C, then B can not make it either.
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int len = gas.length; int ans = 0, remaining = 0, totalRemaining = 0; for(int i = 0; i < len; i++){ totalRemaining += gas[i] - cost[i]; if(remaining < 0){ ans = i; remaining = gas[i] - cost[i]; } else{ remaining += gas[i] - cost[i]; } } if(remaining < 0 || totalRemaining < 0) return -1; return ans; }}
0 0
- LeetCode:Gas Station
- [LeetCode] Gas Station
- [leetcode]Gas Station
- Leetcode: Gas Station
- LeetCode:Gas Station
- [LeetCode] Gas Station
- leetcode Gas Station
- [LeetCode]Gas Station
- LeetCode 之 Gas Station
- leetcode Gas Station
- 【Leetcode】Gas Station
- LeetCode | Gas Station
- LeetCode之Gas Station
- Leetcode: Gas Station
- LeetCode OJ:Gas Station
- [LeetCode]134.Gas Station
- [Leetcode] Gas Station (Java)
- gas station leetcode
- Mysql中where 1=1 和count(0) 使用小技巧
- Leetcode Triangle
- Codeforces Round #363 (Div. 2)[A]Launch of Collider
- Leetcode Rectangle Area
- 在Unity中使用ProtoBuffer进行数值表转换以及生成网络通信用的协议
- Leetcode Gas Station
- CodeForces 346A Alice and Bob
- Codeforces Round #363 (Div. 2)[B]One Bomb
- POJ 3320 Jessica's Reading Problem
- 字节对齐详解
- 应用内跳转百度,高德地图
- 【题】【矩阵】NKOJ 1901 喜欢奇数的面包师
- java基础学习(5)疯狂java讲义第4章课后习题解答源码
- Codeforces Round #363 (Div. 2) [C] Vacations