Maximum Subarray Sum After One Operation - Problem

Imagine you have an array of integers and a special power: you can square exactly one element to potentially boost your maximum subarray sum!

Given an integer array nums, you must perform exactly one operation where you replace any element nums[i] with nums[i] * nums[i] (its square). Your goal is to find the maximum possible sum of any contiguous subarray after this operation.

Key Points:

  • You must square exactly one element (no more, no less)
  • The subarray must be non-empty
  • You want to maximize the sum after the operation

Example: For [2, -1, -4, -3], squaring the -4 gives [2, -1, 16, -3], and the maximum subarray sum becomes 16.

Input & Output

example_1.py โ€” Basic Case
$ Input: [2, -1, -4, -3]
โ€บ Output: 16
๐Ÿ’ก Note: We can square the element -4 to get 16. The modified array becomes [2, -1, 16, -3]. The maximum subarray is [16] with sum 16.
example_2.py โ€” Longer Subarray
$ Input: [1, -1, 1, 1, -1, -1, 1]
โ€บ Output: 4
๐Ÿ’ก Note: We can square one of the -1 elements to get 1. For example, squaring the second element gives [1, 1, 1, 1, -1, -1, 1]. The maximum subarray is [1, 1, 1, 1] with sum 4.
example_3.py โ€” Single Element
$ Input: [-1]
โ€บ Output: 1
๐Ÿ’ก Note: We must square the only element -1 to get 1. The maximum (and only) subarray sum is 1.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • -104 โ‰ค nums[i] โ‰ค 104
  • You must perform exactly one squaring operation

Visualization

Tap to expand
Portfolio Strategy VisualizationDay:2Day 1-1Day 2-4Day 3 โšก-3Day 4Boost Used!(-4)ยฒ = 16Best Portfolio Period:Day 3 only โ†’ Return: 16
Understanding the Visualization
1
Track Two Scenarios
At each day, track the best portfolio return if you've already used your boost, and the best if you haven't used it yet.
2
Decision at Each Step
For each new day, decide whether to extend your current portfolio or start fresh, and whether to use your boost on this day.
3
Optimal Substructure
The best portfolio ending at day i depends on the best portfolios ending at day i-1, creating optimal substructure.
4
Find Maximum
The answer is the maximum 'with boost used' value seen across all days.
Key Takeaway
๐ŸŽฏ Key Insight: By tracking two states (with/without boost used) at each position, we efficiently find the optimal subarray that maximizes the sum after exactly one squaring operation in linear time.
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
28.9K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen