Maximum Score Of Spliced Array solution and explanation
9 more videos on this problem
Leetcode 2321. Maximum Score Of Spliced Array | HindiThinkCode · 7:17 · 2K views
Weekly Contest 299 | 2321. Maximum Score Of Spliced ArraycodingMohan · 14:01 · 1K views
Weekly Contest 299 | Leetcode 2321 Maximum Score Of Spliced Array | DP | Kadane algorithmCoding Decoded · 14:14 · 1K views
2321. Maximum Score Of Spliced Array (Leetcode Hard)Programming Live with Larry · 9:49 · 762 views
Leetcode Weekly contest 299 - Hard - Maximum Score Of Spliced ArrayPrakhar Agrawal · 13:06 · 743 views
Maximum Score Of Spliced Array | Weekly Contest 299Coding Talkies | Newton School · 12:58 · 566 views
Kadane Algorithm Coding Interview Pattern: Leetcode 2321 Maximum Score of Spliced ArrayBharat Khanna · 18:41 · 425 views
【每日一题】LeetCode 2321. Maximum Score Of Spliced ArrayHuifeng Guan · 15:11 · 340 views
Maximum Score Of Spliced Array | 2321 LeetCode | Prefix Sum | Dp | Leetcode Weekly Contest 299CodeWithSunny · 20:35 · 310 views
Maximum Score Of Spliced Array - 2321. LEETCODEWeb Mickey · 18:09 · 193 views
The 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]andnums2 = [11,12,13,14,15]and you chooseleft = 1andright = 2,nums1becomes[1,12,13,4,5]andnums2becomes[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.length1 <= n <= 1051 <= nums1[i], nums2[i] <= 104
Approach overview
Problem Overview: You are given two arrays of equal length. You may choose a single subarray and swap it between the arrays. The goal is to maximize the final sum of either array after the splice. The challenge is identifying which segment swap produces the largest increase.
The key observation: swapping a segment does not change both arrays independently. Instead, it transfers the difference between elements in that segment. If you track how much benefit each position gives when swapped, the task reduces to finding a maximum gain subarray.
Approach 1: Dynamic Programming on Difference Array (Kadane) (Time: O(n), Space: O(1))
Compute the base sums of both arrays first. If you swap a segment from nums2 into nums1, the gain at index i becomes nums2[i] - nums1[i]. Build this implicit difference while iterating and apply Kadane's algorithm to find the maximum subarray sum. That value represents the best possible improvement to sum(nums1). Repeat the same process in the opposite direction using nums1[i] - nums2[i] to see if improving nums2 yields a larger result. The final answer is the maximum of both improved sums. The algorithm scans the arrays once and maintains a running maximum gain, so it runs in O(n) time with O(1) space.
This approach works because any valid splice corresponds exactly to a contiguous segment. Kadane's algorithm efficiently identifies the segment where the cumulative difference produces the highest gain.
Approach 2: Greedy Difference Tracking (Time: O(n), Space: O(1))
The same idea can be implemented using a greedy running-gain tracker rather than explicitly describing it as dynamic programming. While iterating through the arrays, compute the difference between elements and maintain a running gain. If the running gain becomes negative, reset it because continuing the segment would only reduce the final score. Track the maximum gain encountered during the scan. Perform this process twice: once assuming you improve nums1 and once assuming you improve nums2. Each pass evaluates whether starting a new splice or extending the current one produces a better result.
This greedy interpretation is essentially Kadane's algorithm but framed as continuously deciding whether to extend the current splice segment or start a new one. It avoids storing additional arrays and only tracks a few running variables.
Conceptually, the problem blends ideas from Array manipulation and maximum subarray problems commonly solved with Dynamic Programming or Greedy strategies.
Recommended for interviews: The Kadane-based dynamic programming approach is what interviewers expect. It shows you can transform the swap operation into a difference-gain problem and apply a classic maximum subarray algorithm. Starting with the naive thought process about swapping segments demonstrates understanding, but recognizing the Kadane reduction shows strong problem-solving skills.
Approach 1: Dynamic Programming Approach
We'll use a dynamic programming-like approach to evaluate the effect on the scores of swapping subarrays of nums1 with nums2 and vice-versa. By maintaining effective difference arrays, we can decide whether to swap segments to increase the overall array scores.
def maxScore(nums1, nums2):
sum1 = sum(nums1)
sum2 = sum(nums2)
max_diff_1to2 = 0
max_diff_2to1 = 0
cur_diff_1to2 = 0
cur_diff_2to1 = 0
for a, b in zip(nums1, nums2):
cur_diff_1to2 = max(0, cur_diff_1to2 + b - a)
max_diff_1to2 = max(max_diff_1to2, cur_diff_1to2)
cur_diff_2to1 = max(0, cur_diff_2to1 + a - b)
max_diff_2to1 = max(max_diff_2to1, cur_diff_2to1)
return max(sum1 + max_diff_1to2, sum2 + max_diff_2to1)
print(maxScore([60, 60, 60], [10, 90, 10]))public class Main {
public static int maxScore(int[] nums1, int[] nums2) {
int sum1 = 0, sum2 = 0;
for (int num : nums1) sum1 += num;
for (int num : nums2) sum2 += num;
int maxDiffSum1to2 = 0, maxDiffSum2to1 = 0;
int curDiffSum1to2 = 0, curDiffSum2to1 = 0;
for (int i = 0; i < nums1.length; i++) {
curDiffSum1to2 += nums2[i] - nums1[i];
if (curDiffSum1to2 < 0) curDiffSum1to2 = 0;
maxDiffSum1to2 = Math.max(maxDiffSum1to2, curDiffSum1to2);
curDiffSum2to1 += nums1[i] - nums2[i];
if (curDiffSum2to1 < 0) curDiffSum2to1 = 0;
maxDiffSum2to1 = Math.max(maxDiffSum2to1, curDiffSum2to1);
}
return Math.max(sum1 + maxDiffSum1to2, sum2 + maxDiffSum2to1);
}
public static void main(String[] args) {
int[] nums1 = {60, 60, 60};
int[] nums2 = {10, 90, 10};
System.out.println(maxScore(nums1, nums2));
}
}#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int maxScore(vector<int>& nums1, vector<int>& nums2) {
int sum1 = 0, sum2 = 0;
for (int num : nums1) sum1 += num;
for (int num : nums2) sum2 += num;
int maxDiffSum1to2 = 0, maxDiffSum2to1 = 0;
int curDiffSum1to2 = 0, curDiffSum2to1 = 0;
for (int i = 0; i < nums1.size(); ++i) {
curDiffSum1to2 += nums2[i] - nums1[i];
if (curDiffSum1to2 < 0) curDiffSum1to2 = 0;
maxDiffSum1to2 = max(maxDiffSum1to2, curDiffSum1to2);
curDiffSum2to1 += nums1[i] - nums2[i];
if (curDiffSum2to1 < 0) curDiffSum2to1 = 0;
maxDiffSum2to1 = max(maxDiffSum2to1, curDiffSum2to1);
}
return max(sum1 + maxDiffSum1to2, sum2 + maxDiffSum2to1);
}
int main() {
vector<int> nums1 = {60, 60, 60};
vector<int> nums2 = {10, 90, 10};
cout << maxScore(nums1, nums2) << endl;
return 0;
}function maxScore(nums1, nums2) {
let sum1 = nums1.reduce((a, b) => a + b, 0);
let sum2 = nums2.reduce((a, b) => a + b, 0);
let maxDiffSum1to2 = 0, maxDiffSum2to1 = 0;
let curDiffSum1to2 = 0, curDiffSum2to1 = 0;
for (let i = 0; i < nums1.length; i++) {
curDiffSum1to2 = Math.max(0, curDiffSum1to2 + nums2[i] - nums1[i]);
maxDiffSum1to2 = Math.max(maxDiffSum1to2, curDiffSum1to2);
curDiffSum2to1 = Math.max(0, curDiffSum2to1 + nums1[i] - nums2[i]);
maxDiffSum2to1 = Math.max(maxDiffSum2to1, curDiffSum2to1);
}
return Math.max(sum1 + maxDiffSum1to2, sum2 + maxDiffSum2to1);
}
console.log(maxScore([60, 60, 60], [10, 90, 10]));#include <stdio.h>
#include <stdlib.h>
int max(int a, int b) { return a > b ? a : b; }
int maxScore(int* nums1, int* nums2, int n) {
int sum1 = 0, sum2 = 0;
for (int i = 0; i < n; ++i) {
sum1 += nums1[i];
sum2 += nums2[i];
}
int maxDiffSum1to2 = 0, maxDiffSum2to1 = 0;
int curDiffSum1to2 = 0, curDiffSum2to1 = 0;
for (int i = 0; i < n; ++i) {
curDiffSum1to2 += nums2[i] - nums1[i];
if (curDiffSum1to2 < 0) curDiffSum1to2 = 0;
maxDiffSum1to2 = max(maxDiffSum1to2, curDiffSum1to2);
curDiffSum2to1 += nums1[i] - nums2[i];
if (curDiffSum2to1 < 0) curDiffSum2to1 = 0;
maxDiffSum2to1 = max(maxDiffSum2to1, curDiffSum2to1);
}
return max(sum1 + maxDiffSum1to2, sum2 + maxDiffSum2to1);
}
int main() {
int nums1[] = {60, 60, 60};
int nums2[] = {10, 90, 10};
int n = sizeof(nums1) / sizeof(nums1[0]);
printf("%d", maxScore(nums1, nums2, n));
return 0;
}using System;
public class Program {
public static int MaxScore(int[] nums1, int[] nums2) {
int sum1 = 0, sum2 = 0;
foreach (int num in nums1) sum1 += num;
foreach (int num in nums2) sum2 += num;
int maxDiffSum1to2 = 0, maxDiffSum2to1 = 0;
int curDiffSum1to2 = 0, curDiffSum2to1 = 0;
for (int i = 0; i < nums1.Length; i++) {
curDiffSum1to2 += nums2[i] - nums1[i];
if (curDiffSum1to2 < 0) curDiffSum1to2 = 0;
maxDiffSum1to2 = Math.Max(maxDiffSum1to2, curDiffSum1to2);
curDiffSum2to1 += nums1[i] - nums2[i];
if (curDiffSum2to1 < 0) curDiffSum2to1 = 0;
maxDiffSum2to1 = Math.Max(maxDiffSum2to1, curDiffSum2to1);
}
return Math.Max(sum1 + maxDiffSum1to2, sum2 + maxDiffSum2to1);
}
public static void Main() {
int[] nums1 = {60, 60, 60};
int[] nums2 = {10, 90, 10};
Console.WriteLine(MaxScore(nums1, nums2));
}
}Python's idiomatic iteration and aggregation mechanics shine in summarizing elements of each list and calculating impactful swaps via the two core variables, managing diff counts similarly to other implementations.
Space Complexity: O(1), computed in place, no additional storage.
Approach 2: Greedy Approach Using Difference Tracking
This approach involves calculating the sum of the original arrays and determining benefits from swapping segments. A direct greedy evaluation of swapping possibilities at individual positions and maintaining optimal cumulative benefits guides decision-making correlations for the final score estimate.
def maxScore(nums1, nums2):
sum1 = sum(nums1)
sum2 = sum(nums2)
max_gain_1 = 0
max_gain_2 = 0
for a, b in zip(nums1, nums2):
max_gain_1 = max(0, max_gain_1 + b - a)
max_gain_2 = max(0, max_gain_2 + a - b)
return max(sum1 + max_gain_1, sum2 + max_gain_2)
print(maxScore([60, 60, 60], [10, 90, 10]))public class Main {
public static int maxScore(int[] nums1, int[] nums2) {
int sum1 = 0, sum2 = 0;
for (int num : nums1) sum1 += num;
for (int num : nums2) sum2 += num;
int maxGain1 = 0, maxGain2 = 0;
for (int i = 0; i < nums1.length; i++) {
maxGain1 = Math.max(0, maxGain1 + nums2[i] - nums1[i]);
maxGain2 = Math.max(0, maxGain2 + nums1[i] - nums2[i]);
}
return Math.max(sum1 + maxGain1, sum2 + maxGain2);
}
public static void main(String[] args) {
int[] nums1 = {60, 60, 60};
int[] nums2 = {10, 90, 10};
System.out.println(maxScore(nums1, nums2));
}
}function maxScore(nums1, nums2) {
let sum1 = nums1.reduce((a, b) => a + b, 0);
let sum2 = nums2.reduce((a, b) => a + b, 0);
let maxGain1 = 0,
maxGain2 = 0;
for (let i = 0; i < nums1.length; i++) {
maxGain1 = Math.max(0, maxGain1 + nums2[i] - nums1[i]);
maxGain2 = Math.max(0, maxGain2 + nums1[i] - nums2[i]);
}
return Math.max(sum1 + maxGain1, sum2 + maxGain2);
}
console.log(maxScore([60, 60, 60], [10, 90, 10]));#include <stdio.h>
#include <stdlib.h>
int max(int a, int b) { return a > b ? a : b; }
int maxScore(int* nums1, int* nums2, int n) {
int sum1 = 0, sum2 = 0;
for (int i = 0; i < n; ++i) {
sum1 += nums1[i];
sum2 += nums2[i];
}
int maxGain1 = 0, maxGain2 = 0;
for (int i = 0; i < n; ++i) {
maxGain1 = max(0, maxGain1 + nums2[i] - nums1[i]);
maxGain2 = max(0, maxGain2 + nums1[i] - nums2[i]);
}
return max(sum1 + maxGain1, sum2 + maxGain2);
}
int main() {
int nums1[] = {60, 60, 60};
int nums2[] = {10, 90, 10};
int n = sizeof(nums1) / sizeof(nums1[0]);
printf("%d", maxScore(nums1, nums2, n));
return 0;
}using System;
public class Program {
public static int MaxScore(int[] nums1, int[] nums2) {
int sum1 = 0, sum2 = 0;
foreach (int num in nums1) sum1 += num;
foreach (int num in nums2) sum2 += num;
int maxGain1 = 0, maxGain2 = 0;
for (int i = 0; i < nums1.Length; i++) {
maxGain1 = Math.Max(0, maxGain1 + nums2[i] - nums1[i]);
maxGain2 = Math.Max(0, maxGain2 + nums1[i] - nums2[i]);
}
return Math.Max(sum1 + maxGain1, sum2 + maxGain2);
}
public static void Main() {
int[] nums1 = {60, 60, 60};
int[] nums2 = {10, 90, 10};
Console.WriteLine(MaxScore(nums1, nums2));
}
}Python distinguishes itself with notable succinctness, as builtin zip constructs and adaptable loops expedite number of computations relating to swap evaluations.
Space Complexity: O(1), optimization centered processes.
Approach 3: Default Approach
func maximumsSplicedArray(nums1 []int, nums2 []int) int {
s1, s2 := 0, 0
n := len(nums1)
for i, v := range nums1 {
s1 += v
s2 += nums2[i]
}
f := func(nums1, nums2 []int) int {
t := nums1[0] - nums2[0]
mx := t
for i := 1; i < n; i++ {
v := nums1[i] - nums2[i]
if t > 0 {
t += v
} else {
t = v
}
mx = max(mx, t)
}
return mx
}
return max(s2+f(nums1, nums2), s1+f(nums2, nums1))
}Complexity comparison
| Approach | Complexity |
|---|---|
| Dynamic Programming Approach | Time Complexity: O(n), tight loop traversal and simple arithmetic. Space Complexity: O(1), computed in place, no additional storage. |
| Greedy Approach Using Difference Tracking | Time Complexity: O(n), compact iteration and inline computational arithmetic Space Complexity: O(1), optimization centered processes. |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Dynamic Programming (Kadane on Difference) | O(n) | O(1) | Best general solution. Converts splice benefit into a maximum subarray problem. |
| Greedy Difference Tracking | O(n) | O(1) | Same optimal logic implemented with a running gain reset strategy. |
| Bidirectional Gain Evaluation | O(n) | O(1) | Evaluate improvements for both arrays separately to ensure the best final score. |
Frequently asked questions
Is Maximum Score Of Spliced Array easy or hard?
Maximum Score Of Spliced Array is rated Hard on LeetCode because the splice operation hides a maximum subarray transformation. Once the difference-array insight is recognized, the implementation becomes straightforward using Kadane's algorithm.
Maximum Score Of Spliced Array Python/Java solution
Python and Java implementations follow the same logic: compute array sums, iterate through differences, maintain a running maximum subarray gain, and update the best improvement. The algorithm remains O(n) with constant space across all languages including C++, C, and JavaScript.
How to solve Maximum Score Of Spliced Array in O(n)?
First compute the sum of both arrays. Then iterate while calculating the difference nums2[i] - nums1[i] and apply Kadane's algorithm to find the maximum gain segment for improving nums1. Repeat with nums1[i] - nums2[i] to check improvement for nums2. Add the best gain to the respective base sum and return the maximum result.
What is the best approach for Maximum Score Of Spliced Array?
The optimal solution uses Kadane's algorithm on a difference array. Compute the gain of swapping each index (nums2[i] - nums1[i]) and find the maximum subarray sum to determine the best splice segment. Repeat the process in the opposite direction. This runs in O(n) time and O(1) space.
Is Maximum Score Of Spliced Array asked at Google/Amazon/Meta?
Maximum Score Of Spliced Array follows a classic maximum subarray transformation pattern often seen in interviews at companies like Amazon, Google, and Meta. The problem tests recognition of Kadane's algorithm and the ability to convert operations into a gain-based array problem.
What data structure is used in Maximum Score Of Spliced Array?
The solution primarily uses arrays and running variables. The key technique is applying Kadane's algorithm on element-wise differences between the two arrays rather than using additional data structures.
What is the time complexity of Maximum Score Of Spliced Array?
The optimal algorithm runs in O(n) time because it scans the arrays once while maintaining a running maximum gain using Kadane's algorithm. Space complexity is O(1) since only a few variables are tracked during iteration.
