Maximum Sum with at Most Three Two-Element Tiles
Problem statement
You are given an integer array A and at most three tiles. Each tile covers exactly two neighbouring array elements.
- Tiles cannot overlap.
- A tile cannot extend outside the array, even partially.
- You may use fewer than three tiles, including zero.
Return the greatest possible sum of the covered elements.
Function
solution(A: int[]) → intExamples
Example 1
A = [1,2,3,4]return = 10Use two tiles to cover [1,2] and [3,4]. Their combined sum is 10.
Example 2
A = [-5,-2,-1]return = 0Using no tiles is better than covering a negative-sum pair.
Example 3
A = [5,1,1,5,1,1,5]return = 18Cover index pairs (0,1), (2,3) and (5,6). Each pair sums to 6, giving 18.
Example 4
A = [7]return = 0No complete two-element tile fits.
Constraints
0 <= A.length <= 200000.-10^8 <= A[i] <= 10^8.