LeetCode Weekly Contest No. 299 (3/4)

Problem 3. 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 = 2nums1 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.

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.length
  • 1 <= n <= 10^5
  • 1 <= nums1[i], nums2[i] <= 10^4

解题思路:

这个题思路比较简单,构造两个数列的差即可。

设nums1的元素为a_1,a_2,...,a_n,nums2的元素为b_1,b_2,...,b_n

题目是说从中选择一个索引l和一个索引r,nums1和nums2交换l到r的值,再求sum1和sum2的最大值。

这个可以这样理解:

假设我们要使sum1最大化,则我们要找到l和r,使得sum1减去a_la_r再加上b_lb_r的所有值后最大化。

而sum1一开始是定值,所以需要后面的【减去a_la_r再加上b_lb_r】这个值最大化。

构造数列c,使得c_i=b_i-a_i,则需要找到l和r使得c_l+...+c_r最大化。

这就变成了一个最大和子数组的问题,变成了一个非常简单的dp问题。

然后再对sum2使用相同的算法,最大化sum2,两者取一个最大值即可。

于是:

class Solution:
    def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:
        def helper(arr1, arr2):
            """make arr1's sum as large as possible"""
            c = [a2 - a1 for a1, a2 in zip(arr1, arr2)]
            n = len(c)
            dp = [-1e5] * n
            dp[0] = c[0]
            for i in range(n):
                dp[i] = max(dp[i - 1] + c[i], c[i])
            return sum(arr1) + max(dp)

        return max(helper(nums1, nums2), helper(nums2, nums1))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值