Remove Two Elements from Array Ends for Maximum Remaining Sum

viaLeetCode

Problem: Given an array containing both negative and positive numbers, remove exactly two elements — each taken from either end of the array — such that the sum of the remaining elements is maximized. Return the indices of the removed elements.

Constraints: Array can contain negative and positive integers.

Example: For an array where the two smallest-contributing end elements are removed, the remaining sum is maximized; e.g. removing a large negative value from one end and a small value from the other end.

Approach: Since only elements from the two ends can be removed (0, 1, or 2 from the left and the rest from the right totalling 2 removals), enumerate the O(1) split combinations: remove 2 from left, 1 from each end, or 2 from right, and pick the combination that leaves the maximum remaining sum. This can be computed in O(n) using prefix/suffix sums without recomputation, avoiding the initial DP approach.

Add a follow-up question they asked
Remove exactly K elements for maximum sum
asked …
LeaderboardSalary
Language
Account