|
@@ -0,0 +1,94 @@
|
|
|
+struct Solution;
|
|
|
+
|
|
|
+impl Solution {
|
|
|
+ pub fn can_complete_circuit(gas: Vec<i32>, cost: Vec<i32>) -> i32 {
|
|
|
+ let mut gs = gas.iter().sum::<i32>();
|
|
|
+ let mut cs = cost.iter().sum::<i32>();
|
|
|
+
|
|
|
+ if gs < cs {
|
|
|
+ return -1;
|
|
|
+ }
|
|
|
+
|
|
|
+ let mut c = gas[0] - cost[0];
|
|
|
+
|
|
|
+ let mut m = c;
|
|
|
+ let mut mi = 0;
|
|
|
+
|
|
|
+ for i in 1..gas.len() {
|
|
|
+ c += gas[i] - cost[i];
|
|
|
+
|
|
|
+ if c <= m {
|
|
|
+ m = c;
|
|
|
+ mi = i;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ if mi == gas.len() - 1 {
|
|
|
+ 0
|
|
|
+ } else {
|
|
|
+ (mi + 1) as i32
|
|
|
+ }
|
|
|
+ }
|
|
|
+ pub fn can_complete_circuit1(gas: Vec<i32>, cost: Vec<i32>) -> i32 {
|
|
|
+ let n = gas.len();
|
|
|
+
|
|
|
+
|
|
|
+ for i in 0..n {
|
|
|
+ if gas[i] < cost[i] { continue; }
|
|
|
+ if Solution::helper(&gas, &cost, n, gas[i], i, (i+1)%n) {
|
|
|
+ return i as i32;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ -1
|
|
|
+ }
|
|
|
+
|
|
|
+ fn gas_cost_idx(idx: usize, n: usize) -> (usize, usize){
|
|
|
+ if idx == n {
|
|
|
+ (0, n-1)
|
|
|
+ } else if idx == 0 {
|
|
|
+ (0, n-1)
|
|
|
+ } else {
|
|
|
+ (idx, idx-1)
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ fn helper(gas: &Vec<i32>, cost: &Vec<i32>, n: usize, tank_gas: i32, begin_idx: usize, cur_idx: usize) -> bool {
|
|
|
+
|
|
|
+ let (gas_idx, cost_idx) = Solution::gas_cost_idx(cur_idx, n);
|
|
|
+ if tank_gas - cost[cost_idx] >= 0 && cur_idx == begin_idx {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+
|
|
|
+ if tank_gas - cost[cost_idx] < 0 {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+
|
|
|
+ let new_tank_gas = tank_gas - cost[cost_idx] + gas[gas_idx];
|
|
|
+ Solution::helper(gas, cost, n, new_tank_gas, begin_idx, (cur_idx + 1) % n)
|
|
|
+
|
|
|
+
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+#[cfg(test)]
|
|
|
+mod tests {
|
|
|
+ use super::*;
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn test_can_complete_circuit() {
|
|
|
+ let gas = vec![1,2,3,4,5];
|
|
|
+ let cost = vec![3,4,5,1,2];
|
|
|
+ let res = Solution::can_complete_circuit(gas, cost);
|
|
|
+ assert_eq!(res, 3);
|
|
|
+ }
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn test_can_complete_circuit1() {
|
|
|
+ let gas = vec![1,2,3,4,5];
|
|
|
+ let cost = vec![3,4,5,1,2];
|
|
|
+ let res = Solution::can_complete_circuit(gas, cost);
|
|
|
+ assert_eq!(res, 3);
|
|
|
+ }
|
|
|
+}
|