Maximum Score Of Spliced Array — LeetCode 2321 Python Solution
- Problem
- #2321
- Pattern
- Dynamic Programming
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given two 0-indexed integer arrays nums1 and nums2, both of length n. You can choose two integers left and right where 0 <= left <= right < n and swap the subarray nums1[left...right] with the subarray nums2[left...right].
Example
- Input
- nums1 = [60,60,60], nums2 = [10,90,10]
- Output
- 210
- Explanation
- Choosing left = 1 and right = 1, we have nums1 = [60,90,60] and nums2 = [10,60,10].
Python solution
class Solution:
def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:
def f(nums1, nums2):
d = [a - b for a, b in zip(nums1, nums2)]
t = mx = d[0]
for v in d[1:]:
if t > 0:
t += v
else:
t = v
mx = max(mx, t)
return mx
s1, s2 = sum(nums1), sum(nums2)
return max(s2 + f(nums1, nums2), s1 + f(nums2, nums1))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2321. Maximum Score Of Spliced Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2321. Maximum Score Of Spliced Array?
- LeetCode 2321. Maximum Score Of Spliced Array is rated Hard on LeetCode.
- What topics does LeetCode 2321. Maximum Score Of Spliced Array cover?
- LeetCode 2321. Maximum Score Of Spliced Array is tagged Array and Dynamic Programming on LeetCode.