Maximum Subarray Sum After One Operation

medium array dp

Problem

You are given an integer array nums. You must replace exactly one element nums[i] with its square (nums[i] * nums[i]). After performing that single operation, return the maximum possible sum of a contiguous subarray (the subarray must contain at least one element).

Inputnums = [2, -1, -4, -3]
Output17
Square the -4 to get 16, then take the subarray [2, -1, 16] whose sum is 2 - 1 + 16 = 17.

def max_sum_after_operation(nums):
    no_sq = 0
    used = 0
    best = nums[0] * nums[0]
    for x in nums:
        used = max(no_sq + x * x, used + x, x * x)
        no_sq = max(no_sq + x, x)
        best = max(best, used)
    return best
function maxSumAfterOperation(nums) {
  let noSq = 0;
  let used = 0;
  let best = nums[0] * nums[0];
  for (const x of nums) {
    used = Math.max(noSq + x * x, used + x, x * x);
    noSq = Math.max(noSq + x, x);
    best = Math.max(best, used);
  }
  return best;
}
class Solution {
    public int maxSumAfterOperation(int[] nums) {
        int noSq = 0;
        int used = 0;
        int best = nums[0] * nums[0];
        for (int x : nums) {
            used = Math.max(Math.max(noSq + x * x, used + x), x * x);
            noSq = Math.max(noSq + x, x);
            best = Math.max(best, used);
        }
        return best;
    }
}
int maxSumAfterOperation(vector<int>& nums) {
    int noSq = 0;
    int used = 0;
    int best = nums[0] * nums[0];
    for (int x : nums) {
        used = max({ noSq + x * x, used + x, x * x });
        noSq = max(noSq + x, x);
        best = max(best, used);
    }
    return best;
}
Time: O(n) Space: O(1)