Maximum Subarray Sum with Permutations

TypeScript Hard arrays

Task «Maximum Subarray Sum with Permutations»

Given an array of integers, find the maximum subarray sum that can be obtained by performing at most one swap of any two elements in the array (including the case where no swap is performed). The subarray must be contiguous. If a swap is performed, it is applied before searching for the subarray, and any two elements can be swapped (not necessarily from the subarray). Find the maximum possible subarray sum after at most one swap.

Input Format

In the first line, an integer N (1 ≤ N ≤ 10^5) — the length of the array. In the second line, N integers a_i (-10^4 ≤ a_i ≤ 10^4).

Output Format

One integer — the maximum sum of a subarray after at most one permutation.

Examples

Example 1

INPUT
4 1 -2 3 4
OUTPUT
12

Example 2

INPUT
4 2 -1 -2 -3 -4
OUTPUT
4

Example 3

INPUT
shipped [{"id":1,"status":"pending","items":["book"]},{"id":2,"status":"pending","items":[]},{"id":3,"status":"pending","items":["pen","pencil"]}]
OUTPUT
[{"id":1,"status":"shipped","items":["book"]},{"id":2,"status":"pending","items":[]},{"id":3,"status":"shipped","items":["pen","pencil"]}]
main.ts