Maximum Subarray Sum After One Operation — LeetCode 1746 Python Solution
- Problem
- #1746
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(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.