134.go 966 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package main
  2. // It is toooo slow
  3. func canCompleteCircuitOld(gas []int, cost []int) int {
  4. length := len(gas)
  5. for beg := 0; beg < length; beg++ {
  6. curr := (beg + 1) % length
  7. gasLeft := gas[beg] - cost[beg]
  8. for gasLeft >= 0 {
  9. if curr == beg {
  10. return curr
  11. }
  12. gasLeft += gas[curr] - cost[curr]
  13. curr = (curr + 1) % length
  14. }
  15. }
  16. return -1
  17. }
  18. // If car starts at A and can not reach B. Any station between A and B
  19. // can not reach B. (B is the first station that A can not reach.)
  20. // If the total number of gas is bigger than the total number of cost.
  21. // There must be a solution.
  22. func canCompleteCircuit(gas []int, cost []int) int {
  23. var total, sum, beg int
  24. for i := 0; i < len(gas); i++ {
  25. total += gas[i] - cost[i]
  26. sum += gas[i] - cost[i]
  27. if sum < 0 {
  28. beg = i + 1
  29. sum = 0
  30. }
  31. }
  32. if total < 0 {
  33. return -1
  34. }
  35. return beg
  36. }
  37. // func main() {
  38. // println(canCompleteCircuit(
  39. // []int{1, 2, 3, 4, 5},
  40. // []int{3, 4, 5, 1, 2}))
  41. // }