Problem Description
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 applying the operation exactly once. The subarray must be non-empty.
Key Insights
- We can use dynamic programming with two states:
- One state for the maximum sum ending at index i without using the operation.
- Another state for the maximum sum ending at index i where the operation has already been applied.
- At every index, decide whether to:
- Start a new subarray.
- Extend the previous subarray.
- Use the operation on the current element and either start fresh or extend a previous subarray that has not used the operation.
- The answer is the maximum over all subarrays that have exactly one operation applied.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(n) (Can be optimized to O(1) using rolling variables)
Solution
We solve this problem using two dynamic programming arrays: dp_no_op and dp_op.
- dp_no_op[i] is the maximum subarray sum ending at index i without using the squaring operation.
- dp_op[i] is the maximum subarray sum ending at index i after the operation has been applied exactly once.
The recurrence relations are as follows:
- dp_no_op[i] = max(nums[i], dp_no_op[i-1] + nums[i])
- dp_op[i] = max(dp_no_op[i-1] + (nums[i])^2, dp_op[i-1] + nums[i], (nums[i])^2)
The final answer is the maximum value in dp_op over all indices.