Skip to content

Latest commit

 

History

History
101 lines (78 loc) · 3.45 KB

File metadata and controls

101 lines (78 loc) · 3.45 KB

中文文档

Description

Given an integer array nums and two integers firstLen and secondLen, return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen.

The array with length firstLen could occur before or after the array with length secondLen, but they have to be non-overlapping.

A subarray is a contiguous part of an array.

 

Example 1:

Input: nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2
Output: 20
Explanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2.

Example 2:

Input: nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2
Output: 29
Explanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2.

Example 3:

Input: nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3
Output: 31
Explanation: One choice of subarrays is [5,6,0,9] with length 4, and [0,3,8] with length 3.

 

Constraints:

  • 1 <= firstLen, secondLen <= 1000
  • 2 <= firstLen + secondLen <= 1000
  • firstLen + secondLen <= nums.length <= 1000
  • 0 <= nums[i] <= 1000

Solutions

Python3

class Solution:
    def maxSumTwoNoOverlap(self, nums: List[int], firstLen: int, secondLen: int) -> int:
        n = len(nums)
        s = [0] * (n + 1)
        for i in range(1, n + 1):
            s[i] = s[i - 1] + nums[i - 1]
        ans1, ans2, fm, sm = 0, 0, 0, 0
        for i in range(n - firstLen - secondLen + 1):
            fm = max(fm, s[i + firstLen] - s[i])
            ans1 = max(fm + s[i + firstLen + secondLen] - s[i + firstLen], ans1)
        for i in range(n - firstLen - secondLen + 1):
            sm = max(sm, s[i + secondLen] - s[i])
            ans2 = max(sm + s[i + firstLen + secondLen] - s[i + secondLen], ans2)
        return max(ans1, ans2)

Java

class Solution {
    public int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) {
        int n = nums.length;
        int[] s = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            s[i] = s[i - 1] + nums[i - 1];
        }
        int ans1 = 0, ans2 = 0, fm = 0, sm = 0;
        for (int i = 0; i < n - firstLen - secondLen + 1; i++) {
            fm = Math.max(s[i + firstLen] - s[i], fm);
            ans1 = Math.max(fm + s[i + firstLen + secondLen] - s[i + firstLen], ans1);
        }
        for (int i = 0; i < n - firstLen - secondLen + 1; i++) {
            sm = Math.max(s[i + secondLen] - s[i], sm);
            ans2 = Math.max(sm + s[i + firstLen + secondLen] - s[i + secondLen], ans2);
        }
        return Math.max(ans1, ans2);
    }
}

...