Problem 3. 2321. Maximum Score Of Spliced Array
题目描述:
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]
.
- For example, if
nums1 = [1,2,3,4,5]
andnums2 = [11,12,13,14,15]
and you chooseleft = 1
andright = 2
,nums1
becomes[1,12,13,4,5]
andnums2
becomes[11,2,3,14,15]
.
You may choose to apply the mentioned operation once or not do anything.
The score of the arrays is the maximum of sum(nums1)
and sum(nums2)
, where sum(arr)
is the sum of all the elements in the array arr
.
Return the maximum possible score.
A subarray is a contiguous sequence of elements within an array. arr[left...right]
denotes the subarray that contains the elements of nums
between indices left
and right
(inclusive).
Example 1:
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]. The score is max(sum(nums1), sum(nums2)) = max(210, 80) = 210.
Example 2:
Input: nums1 = [20,40,20,70,30], nums2 = [50,20,50,40,20] Output: 220 Explanation: Choosing left = 3, right = 4, we have nums1 = [20,40,20,40,20] and nums2 = [50,20,50,70,30]. The score is max(sum(nums1), sum(nums2)) = max(140, 220) = 220.
Example 3:
Input: nums1 = [7,11,13], nums2 = [1,1,1] Output: 31 Explanation: We choose not to swap any subarray. The score is max(sum(nums1), sum(nums2)) = max(31, 3) = 31.
Constraints:
n == nums1.length == nums2.length
1 <= n <= 10^5
1 <= nums1[i], nums2[i] <= 10^4
解题思路:
这个题思路比较简单,构造两个数列的差即可。
设nums1的元素为
,nums2的元素为
,
题目是说从中选择一个索引l和一个索引r,nums1和nums2交换l到r的值,再求sum1和sum2的最大值。
这个可以这样理解:
假设我们要使sum1最大化,则我们要找到l和r,使得sum1减去到
再加上
到
的所有值后最大化。
而sum1一开始是定值,所以需要后面的【减去到
再加上
到
】这个值最大化。
构造数列c,使得,则需要找到l和r使得
最大化。
这就变成了一个最大和子数组的问题,变成了一个非常简单的dp问题。
然后再对sum2使用相同的算法,最大化sum2,两者取一个最大值即可。
于是:
class Solution:
def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:
def helper(arr1, arr2):
"""make arr1's sum as large as possible"""
c = [a2 - a1 for a1, a2 in zip(arr1, arr2)]
n = len(c)
dp = [-1e5] * n
dp[0] = c[0]
for i in range(n):
dp[i] = max(dp[i - 1] + c[i], c[i])
return sum(arr1) + max(dp)
return max(helper(nums1, nums2), helper(nums2, nums1))