Ctrl K

Two Lines With Transfer Stops

Hard
Two metro lines are given as strictly increasing arrays first and second, listing station numbers in travel order. A station whose number appears in both arrays is a transfer stop. You board at the start of either line and ride to the end, only ever moving forward. At a transfer stop you may switch to the other line and continue from that same station. You can switch as many times as you like. The value of a route is the sum of the numbers of all stations it passes; a transfer stop counts once. Return the largest possible value modulo 10⁹ + 7.
Example 1
first=[1, 5, 6, 9], second=[2, 3, 5, 20] → 30

Start on the second line: 2 + 3 + 5. At the shared stop 5 we could switch, but staying pays more since 20 beats 6 + 9. Total 2 + 3 + 5 + 20 = 30.

Example 2
first=[4, 10, 11], second=[1, 2, 10, 30] → 44

Before 10 the first line is better (4 against 1 + 2), after 10 the second one is (30 against 11): 4 + 10 + 30 = 44.

Example 3
first=[7], second=[3, 5] → 8

No shared stops, so you ride one line end to end: 3 + 5 = 8 beats 7.

Constraints
  • 1 ≤ len(first), len(second) ≤ 10⁵
  • 1 ≤ first[i], second[i] ≤ 10⁷
  • Both arrays are strictly increasing
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWater Between Walls HardLargest Number From Two Rows HardThe Heaviest Reading Day HardFuel Stops Along the Way HardMirror Chunk Split Hard
loading Python…
Input
first=[1, 5, 6, 9], second=[2, 3, 5, 20]
Expected
30

Run checks the first 3 tests in your browser. Submit checks all 105 tests on the server, hidden ones included.