Maximum Subarray Sum After One Operation — LeetCode 1746 Python Solution

MediumLeetCode PremiumArrayDynamic Programming
Problem
#1746
Reading time
2 min

The 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].

Example

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.

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1746. Maximum Subarray Sum After One Operation is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1746. Maximum Subarray Sum After One Operation?
LeetCode 1746. Maximum Subarray Sum After One Operation is rated Medium on LeetCode.
What topics does LeetCode 1746. Maximum Subarray Sum After One Operation cover?
LeetCode 1746. Maximum Subarray Sum After One Operation is tagged Array and Dynamic Programming on LeetCode.
Is LeetCode 1746. Maximum Subarray Sum After One Operation a premium problem?
Yes. LeetCode 1746. Maximum Subarray Sum After One Operation is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview