LeetCode 1746. Maximum Subarray Sum After One Operation Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1746. Maximum Subarray Sum After One Operation

Description

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:

    <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
    
    <li><code>-10<sup>4</sup>&nbsp;&lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
    

Solutions

Solution 1

PythonJavaC++GoRust
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(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !