1096. Maximum Sum Of Two Non Overlapping Subarrays¶
Difficulty: Medium
LeetCode Problem View on GitHub
1096. Maximum Sum of Two Non-Overlapping Subarrays
Medium
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 <= 10002 <= firstLen + secondLen <= 1000firstLen + secondLen <= nums.length <= 10000 <= nums[i] <= 1000
Solution¶
class Solution {
public int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) {
int n = nums.length;
int current_maxi = 0, current_sum = 0, start = 0;
for (int i = 0; i < firstLen; i++) current_sum += nums[i];
if (firstLen + secondLen < n) current_maxi = Math.max(current_maxi, current_sum + solve(nums, firstLen + 1, n - 1, secondLen));
for (int i = firstLen; i < n; i++) {
current_sum += nums[i];
current_sum -= nums[start++];
if (start >= secondLen) current_maxi = Math.max(current_maxi, current_sum + solve(nums, 0, start - 1, secondLen));
if (i + 1 + secondLen < n) current_maxi = Math.max(current_maxi, current_sum + solve(nums, i + 1, n - 1, secondLen));
}
return current_maxi;
}
private int solve(int arr[] , int low, int high, int len) {
int maxi_sum = 0, current_sum = 0, start = low;
for (int i = low; i < low + len; i++) current_sum += arr[i];
maxi_sum = Math.max(maxi_sum , current_sum);
for (int i = low + len; i <= high; i++) {
current_sum += arr[i];
current_sum -= arr[start++];
maxi_sum = Math.max(maxi_sum, current_sum);
}
return maxi_sum;
}
}
Complexity Analysis¶
- Time Complexity:
O(?) - Space Complexity:
O(?)
Approach¶
Detailed explanation of the approach will be added here