[LeetCode] Maximum Score Of Spliced Array

2321. Maximum Score Of Spliced Array

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.

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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
int helper(vector<int>& A, vector<int>& B) {
int ma = 0, sum = accumulate(begin(A), end(A), 0), n = A.size();
for(int i = 0, kadane = 0; i < n; i++) {
kadane = max(kadane + B[i] - A[i], B[i] - A[i]);
ma = max(ma, kadane);
}
return sum + ma;
}
public:
int maximumsSplicedArray(vector<int>& A, vector<int>& B) {
return max(helper(A, B), helper(B, A));
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/26/PS/LeetCode/maximum-score-of-spliced-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.