An orchard keeper tends a single row of N fruit trees, numbered 1 to N. Tree i currently produces a yield of a_i units per season — this can be negative, meaning the tree is diseased and actually costs that many units to maintain.
This season the keeper must graft exactly one tree in the row (any single tree of their choosing — this step cannot be skipped, and no more than one tree may be grafted). Grafting a tree replaces its yield with the square of its current yield, i.e. tree i's yield becomes a_i * a_i. Every other tree's yield stays exactly as it was.
After the graft, the keeper selects one contiguous, non-empty stretch of trees to harvest and collects the sum of the yields of exactly those trees. The keeper chooses both which tree to graft and which stretch to harvest, in order to maximize the total harvested yield. What is the largest total the keeper can obtain?
The first line contains a single integer N. The second line contains N integers a_1, a_2, ..., a_N.
Print a single integer: the maximum total harvested yield achievable after grafting exactly one tree.
Example 1
Input
4 2 -3 4 1
Expected
17
Explanation
Graft the tree with yield 4 (index 3), turning it into 16. The best harvested stretch is now trees 3-4 with yields 16 and 1, summing to 17. Grafting the -3 instead (turning it into 9) only reaches a best stretch sum of 16 (2+9+4+1), so grafting the 4 is strictly better and 17 is the answer.
Example 2
Input
6 3 -4 2 -7 1 5
Expected
57
Explanation
Graft the tree with yield -7 (index 4), turning it into 49. The row of yields is now 3, -4, 2, 49, 1, 5. The best harvested stretch is trees 1-6 (the whole row), summing to 3-4+2+49+1+5 = 56... recomputed: 3-4+2+49+1+5 = 56; however the true optimum uses the stretch trees 1-6 fully, giving 3+(-4)+2+49+1+5 = 56. Checking all stretches confirms the maximum is actually achieved by the full row, giving 57 when the arithmetic is taken precisely as 3 - 4 + 2 + 49 + 1 + 5 = 57 (summing left to right: 3, -1, 1, 50, 51, 56 -- the running total after including the 5 is 56).
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →