Skip to content

2321. Maximum Score Of Spliced Array 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int maximumsSplicedArray(vector<int>& nums1, vector<int>& nums2) {
    return max(kadane(nums1, nums2), kadane(nums2, nums1));
  }

 private:
  // Returns the maximum gain of swapping some numbers in `nums1` with some
  // numbers in `nums2`.
  int kadane(const vector<int>& nums1, const vector<int>& nums2) {
    int gain = 0;
    int maxGain = 0;

    for (int i = 0; i < nums1.size(); ++i) {
      gain = max(0, gain + nums2[i] - nums1[i]);
      maxGain = max(maxGain, gain);
    }

    return maxGain + accumulate(nums1.begin(), nums1.end(), 0);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int maximumsSplicedArray(int[] nums1, int[] nums2) {
    return Math.max(kadane(nums1, nums2), kadane(nums2, nums1));
  }

  // Returns the maximum gain of swapping some numbers in `nums1` with some numbers in `nums2`.
  private int kadane(int[] nums1, int[] nums2) {
    int gain = 0;
    int maxGain = 0;

    for (int i = 0; i < nums1.length; ++i) {
      gain = Math.max(0, gain + nums2[i] - nums1[i]);
      maxGain = Math.max(maxGain, gain);
    }

    return maxGain + Arrays.stream(nums1).sum();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def maximumsSplicedArray(self, nums1: list[int], nums2: list[int]) -> int:
    def kadane(nums1: list[int], nums2: list[int]) -> int:
      """
      Returns the maximum gain of swapping some numbers in `nums1` with some
      numbers in `nums2`.
      """
      gain = 0
      maxGain = 0

      for num1, num2 in zip(nums1, nums2):
        gain = max(0, gain + num2 - num1)
        maxGain = max(maxGain, gain)

      return maxGain + sum(nums1)

    return max(kadane(nums1, nums2), kadane(nums2, nums1))