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: 22
💡 Note: Square the largest element 4 to get 16, total subarray sum: 1+2+3+16 = 22

Constraints

  • 1 ≤ nums.length ≤ 105
  • -104 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Maximum Subarray Sum After One Operation INPUT nums array: 2 i=0 -1 i=1 -4 i=2 -3 i=3 One operation: square one element (-4) * (-4) = 16 Best square choice! Input Values: nums = [2, -1, -4, -3] Length: 4 elements ALGORITHM (DP) 1 Define DP States dp0[i]: max sum without op dp1[i]: max sum with op done 2 Transitions dp0[i] = max(nums[i], dp0[i-1]+nums[i]) dp1[i] = max(nums[i]^2, dp0[i-1]+nums[i]^2, dp1[i-1]+nums[i]) 3 Compute Values i: 0 1 2 3 dp0: 2 1 -3 -6 dp1: 4 3 17 14 Max dp1 = 17 at i=2 4 Return Maximum Result = max(all dp1[i]) = max(4, 3, 17, 14) = 17 FINAL RESULT Optimal subarray found: 2 -1 16 -3 Selected subarray Calculation: 2 + (-1) + 16 = 17 OUTPUT 17 [OK] Maximum achieved! Key Insight: Track two states: dp0 (no operation used yet) and dp1 (operation already used). Squaring negative numbers can turn them positive, potentially maximizing the sum. The answer is the maximum value in dp1 array since we must perform exactly one operation. TutorialsPoint - Maximum Subarray Sum After One Operation | DP Approach
Asked in
Google 45 Facebook 32 Microsoft 28 Amazon 25
23.4K Views
Medium Frequency
~25 min Avg. Time
890 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