Can u provid me the c++ code with the most optimis...

बनाया गया: 25 अक्तूबर 2026

का उपयोग करके उत्तर दिया गया GPT-5.6 Thinking द्वारा Chat01

प्रश्न

IMG-20261025-WA0009.jpg
IMG-20261025-WA0008.jpg

Can u provid me the c++ code with the most optimised solution short and simple passing all the test cases

विचार

Worked for 5s

उत्तर

Yes. The cleanest solution is O(N²) using prefix sums. The important part is that an overlapping element must be counted once with its sign reversed.

cpp
#include <vector> #include <algorithm> #include <climits> using namespace std; int solution(vector<int> &A, int K, int L) { int N = A.size(); vector<int> pre(N + 1, 0); for (int i = 0; i < N; ++i) pre[i + 1] = pre[i] + A[i]; auto sum = [&](int l, int r) { return pre[r] - pre[l]; }; int ans = INT_MIN; for (int i = 0; i + K <= N; ++i) { for (int j = 0; j + L <= N; ++j) { int total = sum(i, i + K) + sum(j, j + L); int left = max(i, j); int right = min(i + K, j + L); if (left < right) total -= 3 * sum(left, right); ans = max(ans, total); } } return ans; }

Why -3 * overlap?

Initially, sum(K fragment) + sum(L fragment) counts every overlapping value twice:

2 × A[i]

But the problem wants it counted once with the opposite sign:

-A[i]

So:

2A[i] - 3A[i] = -A[i]

For example, if the overlapping value is -4:

2(-4) - 3(-4) = -8 + 12 = 4

which correctly changes -4 into +4.

This handles positive/negative values, partial overlap, complete overlap, K=L, K=N/L=N, and the examples shown. Complexity is O(N²) time and O(N) memory.

इस प्रश्नोत्तर को साझा करें