Leetcode #1537: Get the Maximum Score
In this guide, we solve Leetcode #1537 Get the Maximum Score in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given two sorted arrays of distinct integers nums1 and nums2. A valid path is defined as follows: Choose array nums1 or nums2 to traverse (from index-0).
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Greedy, Array, Two Pointers, Dynamic Programming
Intuition
The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.
Moving one pointer at a time keeps the invariant intact and avoids nested loops.
Approach
Place pointers at the left and right ends and move them based on the comparison or target condition.
This yields a clean linear pass after any required sorting.
Steps:
- Set left and right pointers.
- Move a pointer based on the condition.
- Update the best answer while scanning.
Example
Input: nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]
Output: 30
Explanation: Valid paths:
[2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10], (starting from nums1)
[4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] (starting from nums2)
The maximum is obtained with the path in green [2,4,6,8,10].
Python Solution
class Solution:
def maxSum(self, nums1: List[int], nums2: List[int]) -> int:
mod = 10**9 + 7
m, n = len(nums1), len(nums2)
i = j = 0
f = g = 0
while i < m or j < n:
if i == m:
g += nums2[j]
j += 1
elif j == n:
f += nums1[i]
i += 1
elif nums1[i] < nums2[j]:
f += nums1[i]
i += 1
elif nums1[i] > nums2[j]:
g += nums2[j]
j += 1
else:
f = g = max(f, g) + nums1[i]
i += 1
j += 1
return max(f, g) % mod
Complexity
The time complexity is O(n) (after optional sort O(n log n)). The space complexity is O(1).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.