【LeetCode OJ】Gas Station
Problem link:
http://oj.leetcode.com/problems/gas-station/
We can solve this problem by following algorithm.
CompleteCircuit(gas, cost):
let n be the number of stations
// Check if there exists i such that A[i,n] >= 0
if (sum of gas) > (sum of cost)
return -1 // There is no valid i such that A[i,n] is true // Find the first valid i
i = 0 // start station
tank = 0 // the amount of gas in tank
x = 0 // initially, it is valid to go 0 steps from any station
while x < n:
// Each iteration, we have A[i,x] >= 0, and try to go further
j = (i+x) mod n
// refeul at gas[j] and then use cost[j]
tank += gas[j] - cost[j]
// If tank < 0, it is impossible for car to travel from j to its next station
if tank < 0:
// Set j's next station as the new start station
i = (j+1) mod n
x = 0
tank = 0
else:
x += 1 return i
Correctness
Now, we would prove the algorithm above can solve the problem correctly.
Define E[i,k] which is the amout of gas earned of the car starting from i and going k steps (k <= n)
E[i,k] = 0, if k=0
E[i,k] = gas_earn[i] + gas_earn[i+1] + ... + gas_earn[i+k-1], if 0 < k <= n
where gas_earn[i] = gas[i mod n] - cost[i mod n]
So the problem converts to finding some i such that E[i,k]>=0 for k=0,1,...,n.
Firstly we prove that, there exists some i such that E[i,k] >= 0 for k=0,1,...n if and only if sum(gas[0..n-1]) >= sum(cost[0..n-1]).
(=>) If there exists i such that E[i,k] >= 0, for k=0,1,...n, then we have E[i,n] >= 0, that is
gas_earn[i] + gas_earn[i+1] + ... + gas_earn[i+n-1] >= 0
=> gas_earn[0] + gas_earn[1] + ... + gas_earn[n-1] >= 0
=> sum(gas[0..n-1]) - sum(cost[0..n-1]) >= 0
(<=) Assume sum(gas[0..n-1]) >= sum(cost[0..n01]) and we will show that there must exists i such that E[i,k]>=0 for k=0,...,n by induction.
1) For any circuit of n=1 station, we have
E[0,0] = 0
E[0,1] = gas_earn[0] = gas[0]-cost[0] = sum(gas[0..0]) - sum(cost[0..0]) >= 0
2) Now we already know that for any circuit of (n-1) stations, if sum(gas[0..n-2]) >= sum(cost[0..n-2]) then there must exist i, such that E[i,k]>=0 for k=0,...,n-1.
Consider a circuit of n stations with sum(gas[0..n-1]) >= sum(cost[0..n-1]).
Let j be the station with the minimum gas_earn. If gas_earn[j] >= 0, then every gas_earn is non-negative, we have A[i,n]=true for any i=0,1,..,n-1. So we only consider the case of gas_earn[j] < 0. By merging j and j+1 into one station as j' where gas_earn[j'] = gas_earn[j] + gas_earn[j+1], we can obtain a circuit of (n-1) stations with sum(gas) >= sum(cost). Let E'[i,x] denotethe the amout of gas earned of the car starting from i and going k steps (k <= n-1) in this circuit of (n-1) stations, and d is the number of steps to move from i to j (d > 0 since i != j). Then,
E[i,k] = E'[i,x] >= 0, for k = 0, 1, ..., d-1
E[i,k] = E'[i,k-1] >= 0, for k = d+1, ..., n
Now we only need to check E[i,d],
E[i,d] = gas_earn[i] + gas_earn[i+1] + ... + gas_earn[j-1] + gas_earn[j]
E'[i,d] = gas_earn[i] + gas_earn[i+1] + ... + gas_earn[j-1] + gas_earn[j']
=> E[i,d] = E'[i,d] + gas_earn[j] - gas_earn[j'] = E'[i,d] - gas_earn[j]
=> E[i,d] >= 0 (since E'[i,d]>=0 and gas_earn[j]<0)
By the induction, we can claim that there must exist i such that E[i,k]>=0 for k=0,...,n if sum(gas) >= sum(cost).
Thus, the statement is proved.
Secondly, we will prove that, if E[i,k] >=0 for k=0,1,...,x-1 but E[i,x] < 0, then E[i+j, x-j] < 0 for j = 1, 2, ..., x-1.
According to the definition of E[i,k], we have
E[i,x] = gas_earn[i] + gas_earn[i+1] + ... + gas_earn[i+j] + ... + gas_earn[i+x-1]
E[i,j] = gas_earn[i] + gas_earn[i+1] + ... + gas_earn[i+j-1]
E[i+j,x-j] = gas_earn[i+j] + gas_earn[i+j] + ... + gas_earn[i+j+x-j-1]
So we have:
E[i+j,x-j] = E[i,x] - E[i,j] < 0
This means if we have E[i,k] >=0 for k=0,1,...,x-1 but E[i,x] < 0, then it is impossible for car to go n steps starting from i+1, ..., i+x-1. We only need to check E[i+x, k] for k = 0,...,n.
Python Implementation
class Solution:
# @param gas, a list of integers
# @param cost, a list of integers
# @return an integer
def canCompleteCircuit(self, gas, cost):
# There exists i such that the car staring from i
# can travel around the circuit *if and only if*
# sum(gas) >= sum(cost)
if sum(gas) < sum(cost):
return -1 n = len(gas)
i = 0 # start station, can be selected randomly
t = 0 # the amount of gas in the tank, initially 0
x = 0 # the car go x stations further, initially 0
# x=n means the car travel around and back to the start station
while x < n:
# The car is at station j, going x from i
j = (i+x) % n
# refeul gas[j] and spend cost[j] to get next station
t += gas[j] - cost[j]
# It is impossible to get next station, reset and start from j's next station
if t < 0:
t = 0
x = 0
i = (j+1) % n
else: # or go further
x += 1 return i
【LeetCode OJ】Gas Station的更多相关文章
- 【LeetCode练习题】Gas Station
Gas Station There are N gas stations along a circular route, where the amount of gas at station i is ...
- 【LeetCode OJ】Interleaving String
Problem Link: http://oj.leetcode.com/problems/interleaving-string/ Given s1, s2, s3, find whether s3 ...
- 【LeetCode OJ】Reverse Words in a String
Problem link: http://oj.leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reve ...
- LeetCode OJ:Gas Station(加油站问题)
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You ...
- 【LeetCode OJ】Validate Binary Search Tree
Problem Link: https://oj.leetcode.com/problems/validate-binary-search-tree/ We inorder-traverse the ...
- 【LeetCode OJ】Recover Binary Search Tree
Problem Link: https://oj.leetcode.com/problems/recover-binary-search-tree/ We know that the inorder ...
- 【LeetCode OJ】Same Tree
Problem Link: https://oj.leetcode.com/problems/same-tree/ The following recursive version is accepte ...
- 【LeetCode OJ】Symmetric Tree
Problem Link: https://oj.leetcode.com/problems/symmetric-tree/ To solve the problem, we can traverse ...
- 【LeetCode OJ】Binary Tree Level Order Traversal
Problem Link: https://oj.leetcode.com/problems/binary-tree-level-order-traversal/ Traverse the tree ...
随机推荐
- ubuntu14.04LS中安装SSH
我只能说: 蛋疼了 因为 1.曾经12.04和13.10的源已经不能使用了(PS毕竟支持的时间到了) 2网上有好多说是更新源的 , 打开etc/...文件 ,然后粘贴一下他们给的源的地址 或许有些是可 ...
- 再谈HTML
关于WEB 采用B/S计算模式开发的应用程序我们一般称为Web应用程序. WEB三大层面: 网页的结构部分:结构的定义使用HTML语言(超文本标记语言Hyper Text Mark Up Langua ...
- PL/SQL设置编码方式
(2012-10-30 21:38:33) 转载▼ 标签: 杂谈 分类: ORACLE 导出sql文件出现乱码问题,百度之后,发现问题是由于PL/SQL客户端和ORACLE的字符编码设置不一致引起的. ...
- 编程思考 PetShop读后感
标准,插拔式的设计思想建立一致的标准是通向“复用”的通道.分层,使其得到的充分的独立.一个东西如果独立了[不是孤立],这个事物就具有很强大的力量,这个和一个人的成长是相同的道理.所以呢,在写程序的过程 ...
- YUM安装提示PYCURL ERROR 6 - "Couldn't错误的解决办法
当编译PHP时出现如下错误时,找不到头绪 这时,打开DNS vim /etc/resolv.conf 添加一行nameserver 192.168.1.1 完成上一步,则解决该问题 或者:ec ...
- javaMail创建邮件和发送邮件总结
(注: 本文是参考http://www.cnblogs.com/xdp-gacl/p/4216311.html. 感谢博主的精彩的描述) 一, 前期的准备 1, 导入 mail.jar 二, 操作步骤 ...
- Disaster Recovery, High Availability, and Continuous Availability - What's the Difference?
Disaster Recovery, High Availability, and Continuous Availability - What's the Difference? Posted by ...
- bzoj 2456: mode
#include<cstdio> #include<algorithm> using namespace std; int n,t,sum; int main() { scan ...
- partition by
在row_number() over()中的over使用,其后需要配合order by ROW_NUMBER () over (partition by username order by i ...
- Redis系列-存储篇hash主要操作函数小结
阳光透过玻璃,洒在身上,一杯暖茶在手,说不尽的安逸自得,让我有种想再写篇blog的冲动.上篇主要谈了string,这里谈谈hash吧!hash是一些列key value(field value)的映射 ...