Remove Two End Elements for Maximum Remaining Sum

Problem Given an array of positive and negative integers, remove exactly two elements — each taken from either end of the array — so that the sum of the remaining elements is maximised. Return the indices of the two removed elements.

Input / Output

  • Input: array nums of integers (may be negative).
  • Output: the indices of the two removed elements (and/or the resulting maximum sum).

Constraints

  • 2 <= nums.length <= 10^5.
  • Removals are restricted to the ends: each removal peels an element off the current left or right boundary.
  • Exactly two elements must be removed, even if removing them lowers the sum.

Example

  • nums = [-5, 4, 3, -2] → remove index 0 (-5) and index 3 (-2), leaving [4, 3] with sum 7.
  • Tricky case: nums = [4, 5, 6] — all positive, so you are forced to remove; the best is to drop the two smallest end candidates, leaving sum 6 by removing indices 0 and 1.
asked …
LeaderboardSalaryAccount