forked from hijiangtao/LeetCode-with-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathres.ts
More file actions
29 lines (25 loc) · 687 Bytes
/
res.ts
File metadata and controls
29 lines (25 loc) · 687 Bytes
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
function canCompleteCircuit(gas: number[], cost: number[]): number {
const rest = gas.map((gasItem, i) => gasItem - cost[i]);
let remain = 0;
let startIndex = 0;
if (rest.reduce((p,c) => p+c, 0) < 0) {
return -1;
}
let count = rest.length;
for (let i = 0; ; ) {
if (remain + rest[i] < 0) {
remain = 0;
i = (i+1) % rest.length;
startIndex = i;
count =rest.length;
} else {
remain += rest[i];
i = (i+1) % rest.length;
count--;
if (!count && remain >= 0) {
break;
}
}
}
return startIndex;
};