Maximize the sum of two possibly overlapping subarrays of sizes K and L, negating overlapped elements.
Given an array A of n integers (both positive and negative), choose two contiguous fragments, one of size K and one of size L. The two fragments may overlap. Each element contributes to the final sum only once: if it lies in only one fragment it is added with its original sign; if it lies in both, it is added with its sign flipped (negated). Find the maximum possible sum.
Function signature: int solution(vector<int> &A, int K, int L)
Example: A = [1, 3, -4, 2, -2], K = 3, L = 2. Fragments [1, 3, -4] (indices 0-2) and [-4, 2] (indices 2-3). Index 2 (-4) is shared, so it contributes +4. Result: 1 + 3 + 4 + 2 = 10.
Closest LeetCode problem: 1031 (Maximum Sum of Two Non-Overlapping Subarrays), but this variant allows overlap with a sign-flip twist.
Format · Online assessment.
Community answers
Related questions
Find the maximum sum subarray of size k.Find the maximum number of intervals overlapping any time window of size K.Related courses


