To solve this problem, we need to find the maximum sum of two non-overlapping subarrays of given lengths (L) and (M). The subarrays can be in any order (either (L) before (M) or (M) before (L)).
Approach
- Prefix Sum Calculation: Compute the prefix sum array to quickly calculate the sum of any subarray. This helps in reducing the time complexity of subarray sum calculations to (O(1)).
- Two Cases:
- Case 1: The subarray of length (L) comes before the subarray of length (M).
- Case 2: The subarray of length (M) comes before the subarray of length (L).
- Max Sum Calculation: For each case, compute the maximum sum of the first subarray and then find the maximum sum of the second subarray that does not overlap with the first. The result for each case is the sum of these two maximum values.
- Result: The final result is the maximum value from the two cases.
Solution Code
def max_sum_two_non_overlapping(arr, L, M):
# Compute prefix sum array
prefix = [0] * (len(arr) + 1)
for i in range(len(arr)):
prefix[i+1] = prefix[i] + arr[i]
def compute_max(a, b):
# a: length of first subarray, b: length of second subarray
max_a = prefix[a] - prefix[0]
result = max_a + (prefix[a + b] - prefix[a])
# Iterate through possible positions of the second subarray
for i in range(a + 1, len(arr) - b + 1):
current_a = prefix[i] - prefix[i - a]
if current_a > max_a:
max_a = current_a
current_b = prefix[i + b] - prefix[i]
if max_a + current_b > result:
result = max_a + current_b
return result
# Calculate both cases and return the maximum
case1 = compute_max(L, M)
case2 = compute_max(M, L)
return max(case1, case2)
Explanation
- Prefix Sum: The prefix sum array is constructed such that
prefix[i]is the sum of the firstielements of the input array. This allows us to compute the sum of any subarray from indexstarttoendasprefix[end+1] - prefix[start]. - Compute Max Function: This function calculates the maximum sum of two non-overlapping subarrays where the first subarray has length
aand the second has lengthb. It keeps track of the maximum sum of the first subarray encountered so far and uses it to find the maximum sum of the second subarray that does not overlap. - Two Cases: By swapping the lengths (L) and (M), we cover both possible orders of the subarrays and take the maximum of the two results to get the final answer.
This approach efficiently computes the desired result with a time complexity of (O(n)) (where (n) is the length of the input array) and a space complexity of (O(n)) (due to the prefix sum array). This ensures the solution is optimal and handles large input sizes effectively.

作者声明:本文包含人工智能生成内容。