Problem
You are given two sorted arrays of distinct integers nums1 and nums2.
A valid __** path** is defined as follows:
- Choose array
nums1ornums2to traverse (from index-0). - Traverse the current array from left to right.
- If you are reading any value that is present in
nums1andnums2you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path).
The score is defined as the sum of unique values in a valid path.
Return the maximum score you can obtain of all possiblevalid paths.
Since the answer may be too large, return it modulo 10^9 + 7.
Examples
Example 1
| |
Example 2
| |
Example 3
| |
Constraints
1 <= nums1.length, nums2.length <= 10^51 <= nums1[i], nums2[i] <= 10^7nums1andnums2are strictly increasing.
Solution
Method 1 – Two Pointers with Path Sums
Intuition
Since both arrays are sorted and strictly increasing, we can use two pointers to traverse both arrays. At each common element, we can choose to switch arrays, so we keep track of the sum along both paths and always take the maximum sum at each intersection.
Approach
- Initialize two pointers
iandjfornums1andnums2. - Maintain two running sums
sum1andsum2for the current path in each array. - Traverse both arrays:
- If
nums1[i] < nums2[j], addnums1[i]tosum1and movei. - If
nums1[i] > nums2[j], addnums2[j]tosum2and movej. - If
nums1[i] == nums2[j], add the max ofsum1andsum2plus the common value to the answer, reset both sums to 0, and move both pointers.
- If
- After the loop, add the remaining sums from both arrays to the answer.
- Return the answer modulo
10^9 + 7.
Code
| |
| |
| |
| |
| |
| |
| |
Complexity
- ⏰ Time complexity:
O(n + m)— Each element in both arrays is visited at most once. - 🧺 Space complexity:
O(1)— Only a constant amount of extra space is used for pointers and sums.