Maximum Subarray Sum After One Operation - Problem
You are given an integer array nums. You must perform exactly one operation where you can replace one element nums[i] with nums[i] * nums[i].
Return the maximum possible subarray sum after exactly one operation. The subarray must be non-empty.
Note: A subarray is a contiguous part of an array.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,-1,-4,-3]
›
Output:
17
💡 Note:
Square -4 to get 16, then subarray [-1,16] gives sum 15, but subarray [16] alone gives 16, and we can extend to get 17 by including previous elements optimally
Example 2 — Single Element
$
Input:
nums = [1]
›
Output:
1
💡 Note:
Only one element, must square it: 1² = 1
Example 3 — All Positive
$
Input:
nums = [1,2,3,4]
›
Output:
26
💡 Note:
Square the largest element 4 to get 16, total subarray sum: 1+2+3+16 = 22. Wait, let's recalculate: actually we want to square 4 and take whole array: 1+2+3+16=22. But we could also square 1: 1+2+3+4=10 vs 1²+2+3+4=10. Best is square 4: sum=22. Actually, let me verify: square any element and take full array. Square 4: 1+2+3+16=22. That should be the answer, let me double-check the constraint about exactly one operation.
Constraints
- 1 ≤ nums.length ≤ 105
- -104 ≤ nums[i] ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of integers where we must square exactly one element
2
Process
Find optimal element to square and optimal subarray
3
Output
Maximum possible subarray sum after one square operation
Key Takeaway
🎯 Key Insight: Use dynamic programming to track subarrays with and without the square operation simultaneously
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code