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
Maximum Score of Spliced Array INPUT nums1: 60 60 60 [0] [1] [2] nums2: 10 90 10 [0] [1] [2] sum(nums1) = 180 sum(nums2) = 110 Goal: Swap subarray to maximize sum of either array ALGORITHM STEPS 1 Compute Differences diff[i] = nums2[i] - nums1[i] [-50, 30, -50] 2 Kadane's Algorithm Find max subarray sum of diff array: 30 3 Best for nums1 sum1 + maxGain = 180+30 = 210 4 Repeat for nums2 diff2[i] = nums1[i]-nums2[i] [50, -30, 50] sum2 + maxGain = 110+70 = 180 Kadane finds: swap index [1] gains +30 for nums1 FINAL RESULT Optimal: Swap index [1] nums1 after swap: 60 90 60 swapped! New sum(nums1): 60 + 90 + 60 = 210 Maximum Score 210 max(210, 180) = 210 OK - Answer verified! Key Insight: Swapping subarray [left..right] from nums2 to nums1 increases sum(nums1) by sum(nums2[left..right]) - sum(nums1[left..right]). This equals the sum of diff[left..right] where diff[i] = nums2[i] - nums1[i]. Use Kadane's algorithm to find the maximum subarray sum of the difference array. Apply the same logic for maximizing nums2. TutorialsPoint - Maximum Score Of Spliced Array | Optimal Solution
Asked in
Google 15 Facebook 12 Amazon 8
12.5K Views
Medium Frequency
~25 min Avg. Time
423 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen