All problems

Problem 501

Maximum Subarray Sum with One Deletion

Medium · 20 pts · Array, Dynamic Programming

Problem

Choose a non-empty block of consecutive elements, and you may delete at most one element from it, as long as the block is still non-empty afterwards. Find the largest possible sum of what remains. Deleting is optional, so a block with no deletion is also allowed. Keep two running values while scanning: the best sum of a block ending here with no deletion, and with one deletion already used.

Input

The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1].

Output

Print the maximum possible sum.

Constraints

1 <= N <= 100000; -10000 <= A[i] <= 10000

Example input

4
1 -2 0 3

Example output

4

Explanation

In 1 -2 0 3, take the whole array and delete -2: the rest is 1 + 0 + 3 = 4. No other choice does better, so the answer is 4.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Battleships in a Board Next: Longest Ones After Deleting One Element