1746. Maximum Subarray Sum After One Operation
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Solution { public: int maxSumAfterOperation(vector<int>& A) { int n = A.size(), res = 0; vector<int> kadane(n,0); for(int i = 0, sum = 0; i < n; i++) { kadane[i] = sum = max(sum + A[i], 0); } for(int i = n - 1, sum = 0; i >= 0; i--) { res = max(res, A[i] * A[i] + (i ? kadane[i-1] : 0) + sum); sum = max(sum + A[i], 0); } return res; } };
|