We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Get the Maximum Score

Number: 1659

Difficulty: Hard

Paid? No

Companies: Oracle, Mindtickle


Problem Description

Given two sorted arrays of distinct integers, the goal is to construct a valid path by traversing either array from left to right and switching between them at common elements. The score is the sum of the visited elements, and you want to maximize this sum. Since the arrays are sorted, you can only move forward, and at a common element you may choose the path with the highest accumulated sum. Return the maximum score achievable modulo 10^9 + 7.


Key Insights

  • Both arrays are sorted and contain distinct values.
  • Use two pointers to traverse both arrays simultaneously.
  • Maintain two cumulative sums (one for each array) until encountering a common element.
  • At a common element, add the maximum of the two cumulative sums plus the common value and reset both running sums.
  • Once one array is fully processed, add the remaining elements from the other.
  • This approach is both greedy and dynamic programming oriented.

Space and Time Complexity

Time Complexity: O(n + m), where n and m are the lengths of nums1 and nums2 respectively. Space Complexity: O(1) extra space.


Solution

Use two pointers to iterate through both arrays while accumulating sums. When a common element is found:

  1. Add the common element to the maximum of the two cumulative sums.
  2. Set both cumulative sums to this new value.
  3. Continue traversing. Finally, add the remaining values from the array that still has unprocessed elements. Return the maximum of the two cumulative totals modulo 10^9 + 7.

Code Solutions

def maxSum(nums1, nums2):
    MOD = 10**9 + 7
    i, j = 0, 0
    sum1, sum2 = 0, 0  # running sums for nums1 and nums2
    while i < len(nums1) and j < len(nums2):
        if nums1[i] < nums2[j]:
            sum1 += nums1[i]
            i += 1
        elif nums1[i] > nums2[j]:
            sum2 += nums2[j]
            j += 1
        else:
            # When encountering the same number
            common_value = nums1[i]
            sum1 = sum2 = max(sum1, sum2) + common_value
            i += 1
            j += 1
    # Add remaining elements from nums1
    while i < len(nums1):
        sum1 += nums1[i]
        i += 1
    # Add remaining elements from nums2
    while j < len(nums2):
        sum2 += nums2[j]
        j += 1
    return max(sum1, sum2) % MOD

# Example usage:
print(maxSum([2,4,5,8,10], [4,6,8,9]))  # Expected output: 30
← Back to All Questions