-
Notifications
You must be signed in to change notification settings - Fork 0
/
gas_station.rs
58 lines (49 loc) · 1.71 KB
/
gas_station.rs
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// # Gas Station
// There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`.
//
// You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station.
// You begin the journey with an empty tank at one of the gas stations.
//
// Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique
pub fn solution(gas: Vec<i32>, cost: Vec<i32>) -> i32 {
let mut total_tank_size = 0;
let mut current_try_tank_size = 0;
let mut start_item = 0;
let travel_hop = gas.iter().zip(cost.iter());
for (idx, (gas_available, hop_cost)) in travel_hop.enumerate() {
let hop_gas_surplus = gas_available - hop_cost;
total_tank_size += hop_gas_surplus;
current_try_tank_size += hop_gas_surplus;
if current_try_tank_size < 0 {
current_try_tank_size = 0;
start_item = idx as i32 + 1;
}
}
if total_tank_size < 0 {
-1
} else {
start_item
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn example_1() {
let gas = vec![1, 2, 3, 4, 5];
let cost = vec![3, 4, 5, 1, 2];
assert_eq!(solution(gas, cost), 3);
}
#[test]
fn example_2() {
let gas = vec![2, 3, 4];
let cost = vec![3, 4, 3];
assert_eq!(solution(gas, cost), -1);
}
#[test]
fn example_3() {
let gas = vec![5, 1, 2, 3, 4];
let cost = vec![4, 4, 1, 5, 1];
assert_eq!(solution(gas, cost), 4);
}
}