Maximum Subarray Sum After One Operation

Updated on 11 June, 2025
Maximum Subarray Sum After One Operation header image

Problem Statement

In this task, you are given an integer array nums. The objective is to perform a single specific operation where you select an element nums[i] and replace it with its square (nums[i] * nums[i]). After performing this operation exactly once, you need to determine the maximum possible sum of any contiguous subarray within the modified array. It is crucial that the selected subarray is non-empty, meaning it must contain at least one element.

Examples

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

  • 1 <= nums.length <= 10⁵
  • -10⁴ <= nums[i] <= 10⁴

Approach and Intuition

To solve the problem of finding the maximum possible subarray sum after performing exactly one operation (nums[i] = nums[i] * nums[i]), we can use the following approach:

  1. Kadane’s Algorithm Variant:

    • We adapt Kadane’s algorithm, which normally computes the maximum subarray sum in linear time, to handle this special "one square operation" constraint.
  2. Track Two States:

    • For each index i, maintain two states as you iterate:

      • no_square: Maximum subarray sum ending at i without having used the square operation yet.
      • used_square: Maximum subarray sum ending at i where we have already used the square operation.
  3. Transition Between States:

    • When processing nums[i]:

      • For no_square, update it in the normal Kadane style: either extend the current subarray or start new from nums[i].

      • For used_square, consider:

        • Either extending the used_square state with the current number, or
        • Applying the square operation at this position for the first time using the no_square state: no_square + nums[i] * nums[i], or starting new from nums[i] * nums[i].
  4. Track Global Maximum:

    • Keep a global variable max_sum to track the best subarray sum seen so far across both states.

Example Walkthrough

Example 1

Input: nums = [2,-1,-4,-3]

Operations and updates:

At index 2 (value -4), if we apply the square operation, nums[2] becomes 16.
Modified array = [2,-1,16,-3].
Subarray [2, -1, 16] yields sum 17 — this is the maximum.

Example 2

Input: nums = [1,-1,1,1,-1,-1,1]

Operations and updates:

Apply the square operation at index 1 (-1 → 1).
Modified array = [1,1,1,1,-1,-1,1].
Subarray [1,1,1,1] yields sum 4 — this is the maximum.

Summary of Approach

Steps:

  1. Initialize max_sum, no_square, and used_square.

  2. Iterate over the array:

    • Update no_square using standard Kadane logic.
    • Update used_square considering the first square operation or extending the existing one.
    • Update max_sum using both states.
  3. Return max_sum.

Example Insights:

  • For positive numbers, sometimes it is better to apply the square operation to a large negative number to flip it positive.
  • For large positive numbers, squaring them may lead to even larger subarray sums.
  • The dynamic state tracking helps seamlessly manage the transition across all possibilities in one linear pass.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    int maxSumAfterOperation(vector<int>& values) {
        int length = values.size();  // Determine the size of the vector
        
        // Variables to track the maximum sums found.
        int maximumWithoutSquare = values[0];
        int maximumWithSquare = values[0] * values[0];
        int totalMax = maximumWithSquare;  // Initial total max.

        for (int i = 1; i < length; i++) {
            // Calculate maximum sum either by starting fresh or adding to existing sums.
            maximumWithSquare =
                max(max(values[i] * values[i],
                        maximumWithoutSquare + values[i] * values[i]),
                    maximumWithSquare + values[i]);

            // Keep track of sum without squaring in this iteration.
            maximumWithoutSquare =
                max(values[i], maximumWithoutSquare + values[i]);

            // Update the overall maximum sum found so far.
            totalMax = max(totalMax, maximumWithSquare);
        }

        return totalMax;  // Return the overall maximum sum achievable.
    }
};

The provided C++ solution aims to find the maximum subarray sum from a vector of integers, with the additional twist that you can square a single element. Here, maxSumAfterOperation function essentially employs dynamic programming to evaluate both scenarios: where an element of the subarray is squared and where it isn't.

  • Initialization:

    • Define size of the input vector values.
    • Initialize three integers: maximumWithoutSquare, maximumWithSquare, and totalMax. maximumWithoutSquare tracks the highest sum we can achieve without any squaring up to the current element. maximumWithSquare considers the best outcome for blends that include one squared value. totalMax captures the maximum value encountered for any subarray, updated through each iteration.
  • Iterative Comparison:

    • Iterate over vector elements starting from the second element, as the initial values depend on the first element.
    • For maximumWithSquare, determine the larger of three possibilities:
      • Squaring the current element.
      • Adding the squared current element to the best possible sum without squaring before this point.
      • Extending the previous combined scenarios including this element normally.
    • For maximumWithoutSquare, update it with the maximum of either adding the current value to maximumWithoutSquare or just the current value itself.
    • Update the totalMax with the greater value between its current value and maximumWithSquare.
  • Return Value:

    • At the end, totalMax which stores the highest possible sum is returned, providing the maximum subarray sum achievable with one squaring operation.

This approach ensures an optimal evaluation using dynamic programming techniques, considering all possibilities with minimal overhead and effectively handles cases where altering just one element's contribution via squaring may result in an improved outcome.

java
class Solution {

    public int maximumSumWithSquare(int[] elements) {
        int length = elements.length; // Get the length of the input array.

        // Variables to track the maximum possible sums.
        int maxRegularSum = elements[0];
        int maxEnhancedSum = elements[0] * elements[0];
        int overallMaxSum = maxEnhancedSum;

        for (int i = 1; i < length; i++) {
            // Compute the maximum sum for cases involving squaring the current element.
            maxEnhancedSum = Math.max(
                elements[i] * elements[i],
                Math.max(
                    maxRegularSum + elements[i] * elements[i],
                    maxEnhancedSum + elements[i]
                )
            );

            // Compute the maximum sum for regular contiguous subarray.
            maxRegularSum = Math.max(
                elements[i],
                maxRegularSum + elements[i]
            );

            // Update the overall maximum sum.
            overallMaxSum = Math.max(overallMaxSum, maxEnhancedSum);
        }

        return overallMaxSum;
    }
}

The provided Java solution addresses the problem of finding the maximum subarray sum after one operation, where the operation is squaring a single element in the array. Here's how the function maximumSumWithSquare achieves this:

  • Begin by initializing variables to store the maximum sums:

    • maxRegularSum starts as the first element of the array, which tracks the maximum sum of a regular subarray without any operations.
    • maxEnhancedSum starts as the square of the first element, maintaining the maximum sum where exactly one element of any subarray has been squared.
    • overallMaxSum stores the highest value between ordinary and enhanced sums and starts with the value of maxEnhancedSum.
  • Iterate through the array starting from the second element. For each element, two comparisons are made:

    • Update maxEnhancedSum by either:
      • Squaring the current element,
      • Adding the squared current element to the sum of the previous regular subarray,
      • Adding the current element to the sum of the previously enhanced subarray.
    • Update maxRegularSum by taking the larger of:
      • The current element itself (starting a new subarray),
      • Adding the current element to the sum of the previous subarray.
  • Continuously update overallMaxSum with the higher value between the current overallMaxSum and maxEnhancedSum.

  • Return the maximum value stored in overallMaxSum after completing the iterations, which represents the largest possible sum of a subarray after squaring exactly one of its elements.

This solution leverages dynamic programming principles, keeping track of the maximum sums with and without the squaring operation as the array is processed, ensuring an efficient single-pass calculation.

python
class Solution:
    def maximumSumOfSquares(self, integers: list[int]) -> int:
        length = len(integers)  # Determining the length of the integer list.

        # Initializations for maximum sums evaluations.
        max_normal = integers[0]
        max_with_square = integers[0] ** 2
        overall_max = max_with_square

        for i in range(1, length):
            # Calculate max with current element squared, adding squared to previous max, or extending previous.
            max_with_square = max(
                max(
                    integers[i] ** 2,
                    max_normal + integers[i] ** 2
                ),
                max_with_square + integers[i]
            )

            # Calculate max by either starting new or continuing with the previous maximum.
            max_normal = max(
                integers[i], max_normal + integers[i]
            )

            # Keeping track of the global maximum with one element squared.
            overall_max = max(overall_max, max_with_square)

        return overall_max

Achieve the maximum subarray sum with one operation using Python, where one element of the subarray is squared to potentially increase the total sum. Here's how the function maximumSumOfSquares operates to compute this:

  • Define a function named maximumSumOfSquares that accepts a list of integers.
  • Calculate the initial maximum sums using only the first element, with and without squaring it.
  • Iterate through the list starting from the second element, progressively evaluating two scenarios for each number:
    • Compute the maximum sum by squaring the current element and compare it with the sum obtained by adding the squared current element to the previously computed maximum sum without squaring.
    • Continue the subarray sum without squaring any additional element.
  • Update the global maximum in each iteration whenever a new higher sum is encountered with one of the elements squared.
  • Finally, return the global maximum sum after iterating through the list.

This method ensures optimal evaluation by considering both continued sequences and the impact of squaring a single element in enhancing the subarray sum. Keep in mind that the function returns the highest possible sum achievable through one of these adjusted operations.

Comments

No comments yet.