FastPrepMaximum Sum of Two Non-Overlapping Subarrays

Maximum Sum of Two Non-Overlapping Subarrays

Google logoGoogle● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Given an array nums of nonnegative integers and two lengths firstLen and secondLen, choose two non-overlapping contiguous subarrays of those exact lengths. Return the largest possible sum of all elements in the two chosen subarrays.

The subarray of length firstLen may occur before or after the subarray of length secondLen. The two subarrays may touch at a boundary but must not share an index.

Function

maxSumTwoNoOverlap(nums: int[], firstLen: int, secondLen: int) → int

Examples

Example 1

nums = [0,6,5,2,2,5,1,9,4]firstLen = 1secondLen = 2return = 20

Choose [9] and [6,5]; their sums add to 20.

Example 2

nums = [3,8,1,3,2,1,8,9,0]firstLen = 3secondLen = 2return = 29

Choose the length-three subarray [3,8,1] and the length-two subarray [8,9]. Their sums are 12 and 17.

Example 3

nums = [2,1,5,6,0,9,5,0,3,8]firstLen = 4secondLen = 3return = 31

The disjoint windows [5,6,0,9] and [0,3,8] sum to 20 + 11 = 31.

Constraints

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

More Google problems

See Google hiring insights
public int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) {
    // Write your code here
}
nums[0,6,5,2,2,5,1,9,4]
firstLen1
secondLen2
expected20
Checking account…