Maximum Subarray Sum After One Operation Problem
#1746
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1746.
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.
Example 1:
Input: nums = [2,-1,-4,-3]
Output: 17
Explanation: You can perform the operation on index 2 (0-indexed) to make nums = [2,-1,16,-3]. Now, the maximum subarray sum is 2 + -1 + 16 = 17.
Example 2:
Input: nums = [1,-1,1,1,-1,-1,1]
Output: 4
Explanation: You can perform the operation on index 1 (0-indexed) to make nums = [1,1,1,1,-1,-1,1]. Now, the maximum subarray sum is 1 + 1 + 1 + 1 = 4.
Constraints:
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4
Solution
Approach: Dynamic Programming With Two States
Exactly one element has to be replaced by its square. For the subarray that ends at the current element x, keep two values:
f: the best sum when the replacement has not been used yet. This is ordinary Kadane:f = max(f, 0) + x.g: the best sum when the replacement has been used. Eitherxis the squared element, givingmax(f, 0) + x * x(the earlier part has not used the replacement), or we extend a subarray that already used it, givingg + x.
Both are computed from the previous values. The answer is the largest value seen. It is enough to track g alone as the result, since replacing an element by its square never makes the sum smaller, but taking the maximum over f and g is just as correct.
Complexity: O(n) time and O(1) extra space.
from math import inf
class Solution:
def maxSumAfterOperation(self, nums: List[int]) -> int:
f = g = 0
ans = -inf
for x in nums:
ff = max(f, 0) + x
gg = max(max(f, 0) + x * x, g + x)
f, g = ff, gg
ans = max(ans, f, g)
return ans