From 20cc46bcd0cc1e15da296303c3de1f0d229730f6 Mon Sep 17 00:00:00 2001 From: kanna5 Date: Tue, 9 Dec 2025 11:24:48 +0900 Subject: [PATCH] impl: q134 --- solutions/q134/solution.go | 23 ++++++++++++++++++++++ solutions/q134/solution_test.go | 34 +++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 solutions/q134/solution.go create mode 100644 solutions/q134/solution_test.go diff --git a/solutions/q134/solution.go b/solutions/q134/solution.go new file mode 100644 index 0000000..8682c46 --- /dev/null +++ b/solutions/q134/solution.go @@ -0,0 +1,23 @@ +package q134 + +func canCompleteCircuit(gas []int, cost []int) int { + invalidated := 0 + start, current, tank := 0, 0, 0 + + for { + tank = tank + gas[current] - cost[current] + current = (current + 1) % len(gas) + if tank < 0 { + invalidated += (current - start + len(gas)) % len(gas) + if invalidated >= len(gas) || current == start { + return -1 + } + start = current + tank = 0 + } else if current == start { + return start + } + } +} + +var _ = canCompleteCircuit diff --git a/solutions/q134/solution_test.go b/solutions/q134/solution_test.go new file mode 100644 index 0000000..34c42a2 --- /dev/null +++ b/solutions/q134/solution_test.go @@ -0,0 +1,34 @@ +package q134 + +import ( + "testing" +) + +func Test_canCompleteCircuit(t *testing.T) { + tests := []struct { + name string // description of this test case + // Named input parameters for target function. + gas []int + cost []int + want int + }{ + { + gas: []int{1, 2, 3, 4, 5}, + cost: []int{3, 4, 5, 1, 2}, + want: 3, + }, + { + gas: []int{2, 3, 4}, + cost: []int{3, 4, 3}, + want: -1, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := canCompleteCircuit(tt.gas, tt.cost) + if got != tt.want { + t.Errorf("canCompleteCircuit() = %v, want %v", got, tt.want) + } + }) + } +}