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 180 and 180. Best swap gives nums1=[20,20,50,40,30] (sum=160) or nums2=[50,40,20,70,20] (sum=200). But swapping [1,3] gives nums2=[50,40,50,70,20] with sum=230, but nums1=[20,20,20,40,30] has sum=130. Maximum is 230, but optimal is actually swapping nums1[3,4]→nums2[3,4] giving nums1=[20,40,20,40,20] (sum=140) and nums2=[50,20,50,70,30] (sum=220). 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 ArrayOriginal:606060sum = 180109010sum = 110After swap:609060sum = 210106010sum = 80Maximum Score = max(210, 80) = 210
Understanding the Visualization
1
Input
Two arrays with same length
2
Process
Find optimal subarray to swap
3
Output
Maximum possible array sum
Key Takeaway
🎯 Key Insight: Use Kadane's algorithm on difference arrays to find optimal swap in O(n) time
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