Leetcode 1031: Maximum Sum of Two Non-Overlapping Subarrays

grid47
grid47
Exploring patterns and algorithms
Jul 26, 2024 6 min read

You are given an array of integers nums and two integers firstLen and secondLen. Your task is to find the maximum sum of elements from two non-overlapping subarrays of lengths firstLen and secondLen. The subarrays can appear in any order, but they must not overlap.
Problem
Approach
Steps
Complexity
Input: You are given an integer array `nums` and two integers `firstLen` and `secondLen`, representing the lengths of the two subarrays.
Example: nums = [1, 2, 9, 5, 6, 3, 8, 7], firstLen = 2, secondLen = 3
Constraints:
• 1 <= firstLen, secondLen <= 1000
• 2 <= firstLen + secondLen <= 1000
• firstLen + secondLen <= nums.length <= 1000
• 0 <= nums[i] <= 1000
Output: Return the maximum sum of the elements of the two non-overlapping subarrays.
Example: Output: 30
Constraints:
• The sum of the elements from the two non-overlapping subarrays must be maximized.
Goal: The goal is to find two non-overlapping subarrays whose sum is as large as possible.
Steps:
• 1. Use a sliding window to calculate the sum of every subarray of length `firstLen` and `secondLen`.
• 2. Track the maximum sum of subarrays of length `firstLen` up to each index.
• 3. Track the maximum sum of subarrays of length `secondLen` starting from each index.
• 4. Combine the results to maximize the sum of the two non-overlapping subarrays.
Goal: You must implement a solution that handles the constraints efficiently, especially for large inputs.
Steps:
• The solution must handle arrays of up to 1000 elements.
Assumptions:
• The input array always has enough elements for both subarrays.
Input: Input: nums = [1, 2, 9, 5, 6, 3, 8, 7], firstLen = 2, secondLen = 3
Explanation: The optimal choice is to take the subarray [9, 5] with length 2 and [6, 3, 8] with length 3. The sum is 9 + 5 + 6 + 3 + 8 = 30.

Input: Input: nums = [3, 8, 1, 5, 2, 9], firstLen = 2, secondLen = 2
Explanation: One optimal choice is the subarray [8, 1] with length 2 and [5, 2] with length 2. The sum is 8 + 1 + 5 + 2 = 16.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus