Maximum Score Of Spliced Array - 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].
For example, if nums1 = [1,2,3,4,5] and nums2 = [11,12,13,14,15] and you choose left = 1 and right = 2, nums1 becomes [1,12,13,4,5] and nums2 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.
Input & Output
Example 1 — Basic Swap
$
Input:
nums1 = [60,60,60], nums2 = [10,90,10]
›
Output:
210
💡 Note:
Swap index 1: nums1 becomes [60,90,60] with sum 210, nums2 becomes [10,60,10] with sum 80. Maximum is 210.
Example 2 — No Swap Better
$
Input:
nums1 = [20,40,20,70,30], nums2 = [50,20,50,40,20]
›
Output:
220
💡 Note:
Original sums are both 180. Using Kadane's algorithm to find optimal subarray swap: the maximum benefit from swapping is 40, achieved by swapping subarray [0,2] giving nums1=[50,20,50,70,30] (sum=220) and nums2=[20,40,20,40,20] (sum=140). Maximum is 220.
Example 3 — Single Element
$
Input:
nums1 = [100], nums2 = [50]
›
Output:
100
💡 Note:
Can swap to get nums1=[50], nums2=[100], but original nums1 sum of 100 is already maximum.
Constraints
- 1 ≤ nums1.length, nums2.length ≤ 105
- nums1.length == nums2.length
- -104 ≤ nums1[i], nums2[i] ≤ 104
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code