Get the Maximum Score - Problem
Path Navigation with Maximum Score
You are given two sorted arrays of distinct integers
🛣️ Path Rules:
Example: If
Return the maximum possible score modulo 109 + 7.
You are given two sorted arrays of distinct integers
nums1 and nums2. Your goal is to find a path through these arrays that maximizes the sum of values you collect.🛣️ Path Rules:
- Start at index 0 of either array
- Move left-to-right within your current array
- When you encounter a value that exists in both arrays, you can switch paths
- Each unique value is counted only once in your score
Example: If
nums1 = [2,4,5,8,10] and nums2 = [4,6,8,9], you could take path: 2 → 4 → 6 → 8 → 9 for score = 29, or 2 → 4 → 5 → 8 → 10 for score = 29.Return the maximum possible score modulo 109 + 7.
Input & Output
example_1.py — Basic Path Selection
$
Input:
nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]
›
Output:
30
💡 Note:
Optimal path: 2 → 4 → 6 → 8 → 10. At intersection 4, both paths have equal sum (2 vs 0), so we can choose either. At intersection 8, path through nums2 gives us 4+6=10 vs nums1's 4+5=9, so we switch to nums2, then continue to get the maximum ending.
example_2.py — Multiple Intersections
$
Input:
nums1 = [1,3,5,7,9], nums2 = [3,5,100]
›
Output:
109
💡 Note:
Optimal path: 1 → 3 → 5 → 100. Start with nums1 to get 1, then at intersection 3, nums1 path has sum 1 vs nums2's 0, so continue on nums1. At intersection 5, both have equal recent sums, but we can switch to nums2 to get the large value 100.
example_3.py — No Intersections
$
Input:
nums1 = [1,4,5,8,9], nums2 = [2,3,6,7]
›
Output:
35
💡 Note:
Since there are no common elements, we must choose one complete array. nums1 sum = 27, nums2 sum = 18, so we choose nums1 entirely. Wait, that's wrong calculation. nums1=27, nums2=18, but we need to take the path that gives us maximum, which could involve taking some from each. Actually, with no intersections, we take the array with larger sum: nums1 = 1+4+5+8+9 = 27.
Constraints
- 1 ≤ nums1.length, nums2.length ≤ 105
- 1 ≤ nums1[i], nums2[i] ≤ 107
- nums1 and nums2 are strictly increasing
- All elements in each array are distinct
Visualization
Tap to expand
Understanding the Visualization
1
Start Journey
Begin on either highway, tracking toll collections separately
2
Collect Tolls
As you drive, accumulate tolls from your current highway
3
Bridge Decision
At each bridge, compare total tolls and switch to the better highway
4
Reset & Continue
After switching, reset toll counters and continue the journey
5
Final Choice
At journey's end, add the better of the two remaining highway segments
Key Takeaway
🎯 Key Insight: At each intersection, greedily choose the path segment with higher accumulated value. This works because sorted arrays ensure no future intersection will be missed, and past optimal choices remain optimal.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code