1. Problem Understanding

We are given an integer array. We need to find the maximum sum of a contiguous subarray, where we are allowed to square at most one element in that subarray.

Squaring an element means multiplying it by itself.

For example:

Code
Input:  [-1, -2, 3, -2, 3]
Output: 10

Let's understand why the answer is 10.

Choose this subarray:

Code
[3, -2, 3]

Square the element -2:

Code
3 + (-2 * -2) + 3
= 3 + 4 + 3
= 10

Therefore, the maximum subarray sum is 10.

Important conditions:

  • The subarray must be contiguous.
  • We can square zero or one element.
  • We cannot square more than one element.
  • We need to find the maximum possible sum.

2. Understanding the Concept

Before writing the code, let's understand the main algorithm.

The problem is related to Kadane's Algorithm.

What is Kadane's Algorithm?

Kadane's Algorithm is used to find the maximum sum of a contiguous subarray.

For example:

Code
arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]

The maximum subarray is:

Code
[4, -1, 2, 1]

Sum:

Code
4 + (-1) + 2 + 1 = 6

Kadane's Algorithm maintains the maximum subarray sum ending at the current position.

The logic is:

C#
currentSum = Math.Max(arr[i], currentSum + arr[i]);

There are two possibilities:

  1. Start a new subarray from the current element.
  2. Extend the previous subarray by adding the current element.

But our problem has an additional condition: we can square one element.

So, normal Kadane's Algorithm alone is not enough. We need to maintain two different states.

3. Dynamic Programming Approach

We maintain two important variables.

State 1: noSquare

It stores the maximum subarray sum ending at the current index without squaring any element.

State 2: withSquare

It stores the maximum subarray sum ending at the current index after squaring exactly one element.

We also maintain:

State 3: ans

It stores the overall maximum sum found so far.

Why do we need two states?

Consider:

Code
arr = [3, -2, 3]

Without squaring:

Code
3 + (-2) + 3 = 4

With squaring:

Code
3 + 4 + 3 = 10

We need to remember both possibilities because the best decision at the current element depends on what happened previously.

4. Understanding the Formula

Let's understand each formula.

Formula 1: Without Squaring

C#
noSquare = Math.Max(x, noSquare + x);

Here, x represents the current array element.

We have two choices:

  • Start a new subarray using the current element.
  • Continue the previous subarray.

Mathematically:

\[ noSquare = \max(x,\ previousNoSquare+x) \]

Formula 2: With Squaring

When we square the current element, we have three possibilities:

Option 1: Start a new subarray with the squared element.

Code
x * x

Example:

Code
arr[i] = -2

(-2) * (-2) = 4

Option 2: Extend the previous subarray without squaring and square the current element.

Code
previousNoSquare + (x * x)

Example:

Code
Previous subarray sum = 3
Current element = -2

3 + (-2 * -2) = 7

Option 3: Continue the previous subarray where one element was already squared.

Code
previousWithSquare + x

Example:

Code
Previous sum = 7
Current element = 3

7 + 3 = 10

Therefore, the formula becomes:

\[ \begin{aligned} withSquare = \max(&x^2,\\ &previousNoSquare+x^2,\\ &previousWithSquare+x) \end{aligned} \]

Important: We must use the previous noSquare value before updating it. Otherwise, the calculation will be incorrect.

5. Complete C# Code

C#
class Solution {
    public int maximumSubarray(int[] arr) {

        int n = arr.Length;

        // Maximum sum without squaring
        int noSquare = arr[0];

        // Maximum sum with exactly one squared element
        int withSquare = arr[0] * arr[0];

        // Store the overall maximum
        int ans = Math.Max(noSquare, withSquare);

        for (int i = 1; i < n; i++) {

            int x = arr[i];

            // Store the previous value
            int previousNoSquare = noSquare;

            // Case 1: Without squaring
            noSquare = Math.Max(x, noSquare + x);

            // Case 2: With exactly one square
            withSquare = Math.Max(
                Math.Max(x * x, previousNoSquare + x * x),
                withSquare + x
            );

            // Update the maximum answer
            ans = Math.Max(ans,
                Math.Max(noSquare, withSquare));
        }

        return ans;
    }
}

6. Code Explanation – Line by Line

Step 1: Get array length

C#
int n = arr.Length;

This gives the total number of elements in the array.

Step 2: Initialize the variables

C#
int noSquare = arr[0];
int withSquare = arr[0] * arr[0];

We initialize both states using the first element.

Why?

  • noSquare considers the original element.
  • withSquare considers the squared element.

Step 3: Initialize the answer

C#
int ans = Math.Max(noSquare, withSquare);

We compare both possibilities and store the maximum.

Step 4: Traverse the array

C#
for (int i = 1; i < n; i++)

We start from index 1 because index 0 is already initialized.

Step 5: Store the current element

C#
int x = arr[i];

This makes the formula easier to understand.

Step 6: Preserve the previous state

C#
int previousNoSquare = noSquare;

This is very important.

We need the previous noSquare value to calculate the squared state correctly.

Step 7: Calculate the normal maximum subarray

C#
noSquare = Math.Max(x, noSquare + x);

Either start a new subarray or extend the existing one.

Step 8: Calculate the maximum subarray with one square

C#
withSquare = Math.Max(
    Math.Max(x * x, previousNoSquare + x * x),
    withSquare + x
);

We compare all three possibilities:

  1. Start with the squared current element.
  2. Extend the previous normal subarray and square the current element.
  3. Extend the previous subarray that already used its square.

Step 9: Update the answer

C#
ans = Math.Max(ans,
    Math.Max(noSquare, withSquare));

We compare the maximum sums from both states.

Step 10: Return the result

C#
return ans;

Finally, return the maximum subarray sum.

7. Dry Run – Step-by-Step Execution

Input:

Code
arr = [-1, -2, 3, -2, 3]

Initial values:

Code
noSquare   = -1
withSquare = 1
ans        = 1

Let's process each element.

IndexxnoSquarewithSquareans
0-1-111
1-2-244
23377
3-2157
4341010

Let's understand the important iterations.

Index 1: Current element = -2

Previous values:

Code
noSquare = -1
withSquare = 1

Without squaring:

Code
Max(-2, -1 + -2)
Max(-2, -3) = -2

With squaring:

Code
Option 1: (-2) * (-2) = 4

Option 2: -1 + 4 = 3

Option 3: 1 + (-2) = -1

Maximum = 4

Index 2: Current element = 3

Previous values:

Code
noSquare = -2
withSquare = 4

Without squaring:

Code
Max(3, -2 + 3)
= Max(3, 1)
= 3

With squaring:

Code
Option 1: 3 * 3 = 9

Option 2: -2 + 9 = 7

Option 3: 4 + 3 = 7

Maximum = 9

Correction to the table: At index 2, withSquare is 9, not 7.

Index 4: Current element = 3

The best subarray is:

Code
[3, -2, 3]

Square -2:

Code
3 + 4 + 3 = 10

Final answer:

10

8. Second Example

Input:

Code
arr = [-4, -4, -2, 5, 2, -1]

The best subarray is:

Code
[5, 2]

Square the first element:

Code
5 * 5 + 2
= 25 + 2
= 27

Output:

Code
27

9. Complexity Analysis

ComplexityValueExplanation
Time ComplexityO(n)We traverse the array only once.
Auxiliary SpaceO(1)We use only a fixed number of variables.

This is efficient for an array containing up to 100,000 elements.

10. Important Interview Points

Remember these concepts when solving similar Dynamic Programming problems:

  1. Kadane's Algorithm finds the maximum contiguous subarray sum.
  2. Dynamic Programming stores previous results to avoid recalculating them.
  3. Multiple DP states help track different conditions.
  4. Always preserve previous state values when updating dependent DP states.
  5. Math.Max() helps compare different possible choices.

How to identify this pattern in future problems:

If a problem asks for the maximum subarray sum with an additional operation, such as:

  • Squaring at most one element.
  • Deleting one element.
  • Replacing one element.
  • Allowing one special operation.

Think about extending Kadane's Algorithm with additional DP states.

Final takeaway: The key idea is to maintain two DP states: one for a subarray without squaring and another for a subarray that has already used its one allowed square. This lets us solve the problem in O(n) time and O(1) space.