-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCanCompleteCircuit.java
More file actions
34 lines (30 loc) · 1.03 KB
/
CanCompleteCircuit.java
File metadata and controls
34 lines (30 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.company;
import org.junit.Test;
public class CanCompleteCircuit {
public int canCompleteCircuit(int[] gas, int[] cost) {
/**
* I have thought for a long time and got two ideas:
*
* If car starts at A and can not reach B.
* Any station between A and B can not reach B.
* (B is the first station that A can not reach.)
* If the total number of gas is bigger than the total number of cost.
* There must be a solution.(Should I prove them?)
* Here is my solution based on those ideas:
*/
int start = 0;
int total = 0;
int tank = 0;
//if car fails at 'start', record the next station
for (int i = 0; i < gas.length; i++)
if ((tank = tank + gas[i] - cost[i]) < 0) {
start = i + 1;
total += tank;
tank = 0;
}
return (total + tank < 0) ? -1 : start;
}
@Test
public void test() {
}
}