2321. Maximum Score Of Spliced Array
Question
You are given two 0-indexed integer arrays
nums1andnums2, both of lengthn.You can choose two integers
leftandrightwhere0 <= left <= right < nand swap the subarraynums1[left...right]with the subarraynums2[left...right].
- For example, if
nums1 = [1,2,3,4,5]andnums2 = [11,12,13,14,15]and you chooseleft = 1andright = 2,nums1becomes[1,<strong><u>12,13</u></strong>,4,5]andnums2becomes[11,<strong><u>2,3</u></strong>,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)andsum(nums2), wheresum(arr)is the sum of all the elements in the arrayarr.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 ofnumsbetween indicesleftandright(inclusive).
Solution
滑动窗口。一开始想用dp解决的。
后来发现可以优化到直接记录连续的最大差值即可。
以后有提到连续的一定要想到滑动窗口实现。
辅助方法getMinContigouousDiff()用来计算两个数组间连续的最小的差值和。
当sum为负数时,窗口向右侧扩展,将新的位置加入sum,并更新最小值min。
当扩展后sum大于0时,则放弃之前的所有元素,将sum归零。
最后返回最小值min。
计算两个数组的所有数字之和t1和t2。分别计算nums1[]和nums2[]的差min1和nums2[]和nums1[]的差min2。
在其中替换连续的部分则为t1-min1,t2-min2。取两者中较大的数字返回即可。
Code
1 | class Solution { |
2321. Maximum Score Of Spliced Array
https://xuanhe95.github.io/2022/06/26/2321-Maximum-Score-Of-Spliced-Array/
