内容中心

2026年知名的澳洲移民方案规划条件专业公司推荐-北京澳创移民

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

  1. 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)).
  2. 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).
  3. 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.
  4. 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

  1. Prefix Sum: The prefix sum array is constructed such that prefix[i] is the sum of the first i elements of the input array. This allows us to compute the sum of any subarray from index start to end as prefix[end+1] - prefix[start].
  2. Compute Max Function: This function calculates the maximum sum of two non-overlapping subarrays where the first subarray has length a and the second has length b. 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.
  3. 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.

北京澳创移民



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

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?