Ctrl K

Best Run With One Square

Medium
You get an integer array values. You must perform exactly one operation: pick one element and replace it with its square. After that, take the contiguous non-empty segment with the largest sum. Return the largest such sum you can reach by choosing the element to square in the best way.
Example 1
values=[3, -2, -5, 1] → 27

Square the −5: the array becomes [3, −2, 25, 1], and the whole of it sums to 3 − 2 + 25 + 1 = 27.

Example 2
values=[1, -3, 1] → 11

Squaring −3 gives 9, and then the whole array sums to 1 + 9 + 1 = 11, which beats squaring a 1.

Example 3
values=[0] → 0

The operation is mandatory, but 0² = 0, so the answer is 0.

Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • -10⁴ ≤ values[i] ≤ 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFewest Jumps to the End MediumMost Profitable Streak MediumReach the Last Cell MediumWarehouse Cart Routes MediumCheapest Corner-to-Corner Route Medium
loading Python…
Input
values=[3, -2, -5, 1]
Expected
27

Run checks the first 3 tests in your browser. Submit checks all 110 tests on the server, hidden ones included.