#1537

Get the Maximum Score

Hard
ArrayTwo PointersDynamic ProgrammingGreedyTwo PointersDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses a two-pointer technique to traverse both arrays simultaneously, leveraging the fact that they are sorted. This allows us to efficiently calculate the maximum score by only considering segments between common elements.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize two pointers for nums1 and nums2, and variables to keep track of the current sum and maximum score.
  2. 2Step 2: Traverse both arrays using the pointers, adding values to the current sum until a common element is found.
  3. 3Step 3: When a common element is encountered, compare the current sum with the maximum score and update accordingly.
  4. 4Step 4: Move the pointer of the array that has the smaller current element to continue traversing.
  5. 5Step 5: After reaching the end of both arrays, return the maximum score.
solution.py30 lines
1# Full working Python code
2
3def maxScore(nums1, nums2):
4    i, j = 0, 0
5    sum1, sum2 = 0, 0
6    max_score = 0
7    MOD = 10**9 + 7
8
9    while i < len(nums1) and j < len(nums2):
10        if nums1[i] < nums2[j]:
11            sum1 += nums1[i]
12            i += 1
13        elif nums1[i] > nums2[j]:
14            sum2 += nums2[j]
15            j += 1
16        else:
17            max_score = max(max_score, sum1 + sum2 + nums1[i])
18            sum1 = sum2 = 0
19            i += 1
20            j += 1
21
22    while i < len(nums1):
23        sum1 += nums1[i]
24        i += 1
25    while j < len(nums2):
26        sum2 += nums2[j]
27        j += 1
28
29    max_score = max(max_score, sum1 + sum2)
30    return max_score % MOD

Complexity note: The time complexity is O(n) because we traverse each array only once using two pointers, leading to a linear number of operations.

  • 1Common elements serve as transition points between the two arrays.
  • 2The problem can be efficiently solved using a two-pointer technique due to the sorted nature of the arrays.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.