1589. Richest Merge Route
Two trails, a and b, are strictly increasing singly linked lists of treasure values. A hiker starts at the head of either list and walks forward, and may switch to the other list only at a value that appears in both. Return the route with the maximum total value as a new list; a value shared by both lists is collected once. Between two consecutive shared values, or before the first and after the last, take the segment of the richer list, and prefer the segment from a when the sums tie. Use two pointers for O(n + m) time.
Example 1
- Input:
- a = [1,4,5,8], b = [2,4,6,8]
- Output:
- [2,4,6,8]
- Explanation:
Between the shared values 4 and 8 list a offers 5 and list b offers 6, so b wins; the route is 2, 4, 6, 8.
Example 2
- Input:
- a = [1,2,3], b = [4,5,6]
- Output:
- [4,5,6]
- Explanation:
No value is shared, so the route is simply the richer list: 4, 5, 6.
Example 3
- Input:
- a = [3,7], b = [3,7]
- Output:
- [3,7]
- Explanation:
Both lists are equal, and the route is 3, 7.
Constraints
1 ≤ length of a, length of b ≤ 1000
Both lists are strictly increasing
-106 ≤ val ≤ 106
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n + m)
- Space
- O(n + m)