Блог пользователя Adiix

Автор Adiix, история, 5 недель назад, По-английски

I've been trying to solve this problem:

https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/description/

Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.

Note that the subarray needs to be non-empty after deleting one element."

but I'm unable to think how to approach this problem.. :| any help anyone please?! I tried understanding from LLMs videos but failed to..

  • Проголосовать: нравится
  • -3
  • Проголосовать: не нравится

»
5 недель назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Are you familiar with the standard Kadane's max subarray sum?

Then how can you apply that kind of idea to this problem?

Spoiler
»
5 недель назад, скрыть # |
Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

The problem requires you to take a :

1) Consecutive non-empty subarray.

2) Or a subarray that has an element missed in the middle of it.

For the first case, see Kadane's Algorithm explanation here :

https://www.geeksforgeeks.org/dsa/largest-sum-contiguous-subarray/

Now let's see the second case where we should find a consecutive subarray from L to R.. but there is an index i such that L < i < R missed, let's iterate over all possible 'i' that may be missed .. then we have to find some L and R such that the sum of two segments (L->i-1), (i+1->R) is maximized.. this can be done using prefix sums.

I've implemented the solution and got accepted :


void nl() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; int ans = *max_element(all(a)); // initial value for the answer (taking a segment with length 1) you can initialize it with -inf also. vector<int> pre(n + 1), suf(n + 2); for (int i = 0; i < n; i++) pre[i + 1] = pre[i] + a[i]; for (int i = n - 1; i >= 0; i--) suf[i + 1] = suf[i + 2] + a[i]; vector<int> premn(n + 1), sufmn(n + 2); for (int i = 0; i < n; i++) premn[i + 1] = min(premn[i], pre[i + 1]); for (int i = n - 1; i >= 0; i--) sufmn[i + 1] = min(sufmn[i + 2], suf[i + 1]); for (int i = 0; i < n; i++) { ans = max(ans, pre[i + 1] - premn[i]); // this is the same as Kadane's Algorithm if (i + 1 < n){ // ensuring that we take at least one element from the right side (to ensure that the segment is non-empty) ans = max(ans, pre[i] - premn[i] + suf[i + 2] - sufmn[i + 3]); } if (i > 0){ // ensuring that we take at least one element from the left side (to ensure that the segment is non-empty) ans = max(ans, pre[i] - premn[i - 1] + suf[i + 2] - sufmn[i + 2]); } } cout << ans << '\n'; }