Get the Maximum Score — LeetCode 1537 Python Solution
HardGreedyArrayTwo PointersDynamic Programming
- Problem
- #1537
- Pattern
- Two Pointers
- Reading time
- 4 min
- Source
- leetcode.com
The problem
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).
Example
- Input
- nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]
- Output
- 30
- Explanation
- Valid paths:
Python solution
Python
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) % modComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) (after optional sort O(n log n)) |
| Space | O(1) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 1537. Get the Maximum Score is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1537. Get the Maximum Score?
- LeetCode 1537. Get the Maximum Score is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1537. Get the Maximum Score?
- The Python solution on this page runs in O(n) (after optional sort O(n log n)).
- What is the space complexity of LeetCode 1537. Get the Maximum Score?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1537. Get the Maximum Score cover?
- LeetCode 1537. Get the Maximum Score is tagged Greedy, Array, Two Pointers and Dynamic Programming on LeetCode.