Problem
You are given two sorted arrays of distinct integers nums1
and nums2
.
A valid __** path** is defined as follows:
- Choose array
nums1
ornums2
to traverse (from index-0). - Traverse the current array from left to right.
- If you are reading any value that is present in
nums1
andnums2
you 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^5
1 <= nums1[i], nums2[i] <= 10^7
nums1
andnums2
are 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
i
andj
fornums1
andnums2
. - Maintain two running sums
sum1
andsum2
for the current path in each array. - Traverse both arrays:
- If
nums1[i] < nums2[j]
, addnums1[i]
tosum1
and movei
. - If
nums1[i] > nums2[j]
, addnums2[j]
tosum2
and movej
. - If
nums1[i] == nums2[j]
, add the max ofsum1
andsum2
plus 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.