Get the Maximum Score

Walk two sorted arrays in lockstep; at each shared element take the better of the two intermediate sums.

Hard
Time O(n + m) Space O(1)
LeetCode
5 min read
two-pointers array dp

Problem#

Two strictly-increasing arrays nums1, nums2. A valid path starts at index 0 of either array, may jump to the other array at any shared value, and must end at the last index of either array. Return the maximum path sum mod 10⁹ + 7.

Examples#

  • nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]30 (path: 2 → 4 → 6 → 8 → 10)

Constraints#

  • 1 <= n, m <= 10^5, values up to 10⁷.

Hints#

Hint 1
At every shared value, you can freely choose the larger of the two side sums accumulated since the last shared value.

Approach#

Two pointers merge through the arrays. Maintain running sums s1, s2 since the last shared value. When nums1[i] == nums2[j], both pointers advance; commit max(s1, s2) + nums1[i] to the answer and reset both running sums to zero.

Solution#

Get the Maximum Score
class Solution {
public:
int maxSum(vector<int>& nums1, vector<int>& nums2) {
const int MOD = 1'000'000'007;
long long s1 = 0, s2 = 0, ans = 0;
int i = 0, j = 0;
const int n = nums1.size(), m = nums2.size();
while (i < n && j < m) {
if (nums1[i] < nums2[j]) s1 += nums1[i++];
else if (nums1[i] > nums2[j]) s2 += nums2[j++];
else {
ans += max(s1, s2) + nums1[i];
s1 = s2 = 0;
++i; ++j;
}
}
while (i < n) s1 += nums1[i++];
while (j < m) s2 += nums2[j++];
ans += max(s1, s2);
return ans % MOD;
}
};

Editorial#

The arrays are strictly increasing, so a merge-style walk classifies each element as exclusive to its side until a shared value is found. Between consecutive shared values the optimal path picks the heavier side — switching mid-segment is impossible since there’s no shared element to jump from. The modulo is taken at the end (using long long keeps intermediate sums exact, since values ≤ 10⁷ × length 10⁵ = 10¹², well within signed 64-bit).

Complexity#

  • Time: O(n + m) — merge walk.
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.