Sequence Walking
Time limit1sMemory limit128 MB
Given two ascending integer sequences, find the maximum sum of a forward walk that may switch sequences at shared values.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Two pointers
- Solved
- No attempts yet
Problem
Two finite integer sequences sorted in ascending order are given. A value contained in both sequences can be regarded as a crossing point where the two sequences meet.

The two sequences are shown below, with the crossing points in bold.
- Sequence 1 = 3 5 7 9 20 25 30 40 55 56 57 60 62
- Sequence 2 = 1 4 7 11 14 25 44 47 55 57 100
You walk along these two sequences under the following rules.
- Start at the first element of one of the two sequences. You may only move forward (toward larger values).
- Whenever you reach a crossing point, you may either keep following the current sequence or switch to the other sequence.
- The walk ends when there is no next element to move to, that is, when you reach the last element of the sequence you are currently on.
Find the maximum possible sum of all elements visited along such a walk. For example, walking 3, 5, 7, 9, 20, 25, 44, 47, 55, 56, 57, 60, 62 over the two sequences above gives a sum of 450, which is the maximum attainable.
Input
The input consists of several test cases. Each test case is given on two lines, one line per sequence.
Each line begins with the length of the sequence, followed by its integers in ascending order, separated by spaces. The length satisfies , and every element is an integer with .
The last line of the input contains a single , which marks the end of the input.
Output
For each test case, print the maximum obtainable sum on its own line.