LeetCode 1031: Maximum Sum of Two Non-Overlapping Subarrays Solution
Master LeetCode problem 1031 (Maximum Sum of Two Non-Overlapping Subarrays), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1031. Maximum Sum of Two Non-Overlapping Subarrays
Problem Explanation
Explanation
To solve this problem, we can use a dynamic programming approach. We will iterate over the input array nums and calculate the prefix sums. Then, we will find the maximum sum of subarrays with lengths firstLen and secondLen by considering all possible combinations where the two subarrays do not overlap. We will keep track of the maximum sum found so far.
- Calculate the prefix sums of the input array
nums. - Iterate over the array and consider all possible combinations of non-overlapping subarrays with lengths
firstLenandsecondLen. - Update the maximum sum if a new maximum is found.
- Return the maximum sum.
Time Complexity: O(n) where n is the size of the input array nums.
Space Complexity: O(n) for storing the prefix sums.
Solution Code
class Solution {
public int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) {
int n = nums.length;
int[] prefixSums = new int[n + 1];
for (int i = 0; i < n; i++) {
prefixSums[i + 1] = prefixSums[i] + nums[i];
}
int result = 0;
for (int i = 0; i <= n - firstLen; i++) {
int sum1 = prefixSums[i + firstLen] - prefixSums[i];
for (int j = i + firstLen; j <= n - secondLen; j++) {
int sum2 = prefixSums[j + secondLen] - prefixSums[j];
result = Math.max(result, sum1 + sum2);
}
}
for (int i = 0; i <= n - secondLen; i++) {
int sum1 = prefixSums[i + secondLen] - prefixSums[i];
for (int j = i + secondLen; j <= n - firstLen; j++) {
int sum2 = prefixSums[j + firstLen] - prefixSums[j];
result = Math.max(result, sum1 + sum2);
}
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1031 (Maximum Sum of Two Non-Overlapping Subarrays)?
This page provides optimized solutions for LeetCode problem 1031 (Maximum Sum of Two Non-Overlapping Subarrays) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1031 (Maximum Sum of Two Non-Overlapping Subarrays)?
The time complexity for LeetCode 1031 (Maximum Sum of Two Non-Overlapping Subarrays) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1031 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1031 in Java, C++, or Python.