The Flip to Maximize 1s problem is a classic algorithm problem often asked in coding interviews. The task is:

Given an array of 0s and 1s, you are allowed to flip at most one contiguous subarray (change 0 → 1 and 1 → 0). Return the maximum number of 1s that can be obtained after this operation.

Problem Example

Example 1:

Input: arr = [1, 0, 0, 1, 0]
Output: 4

Explanation:

Example 2:

Input: arr = [1, 1]
Output: 2

Explanation:

Key Insight

To solve the problem efficiently:

  1. Flipping 0 → 1 increases the number of 1s by +1.

  2. Flipping 1 → 0 decreases the number of 1s by -1.

If we create a gain array where:

Then, finding the best subarray to flip is equivalent to finding the maximum sum subarray of this gain array.

We can solve this using Kadane’s Algorithm in O(n) time.

Java Implementation

class Solution {
    int maxOnes(int[] arr) {
        int n = arr.length;
        int totalOnes = 0;

        // Step 1: Count total 1s in the original array
        for (int num : arr) {
            if (num == 1) totalOnes++;
        }

        int maxGain = 0;        // maximum gain from flipping a subarray
        int currentGain = 0;    // current sum of gain subarray

        // Step 2: Find the maximum gain subarray using Kadane's algorithm
        for (int i = 0; i < n; i++) {
            int value = (arr[i] == 0) ? 1 : -1;        // gain for current element
            currentGain = Math.max(value, currentGain + value); // extend or start new subarray
            maxGain = Math.max(maxGain, currentGain);  // track maximum gain
        }

        // Step 3: Maximum 1s = original ones + maximum gain from flip
        return totalOnes + maxGain;
    }
}

How the Code Works

Step 1: Count Original Ones

for (int num : arr) {
    if (num == 1) totalOnes++;
}

Step 2: Convert to Gain and Apply Kadane's Algorithm

int value = (arr[i] == 0) ? 1 : -1;
currentGain = Math.max(value, currentGain + value);
maxGain = Math.max(maxGain, currentGain);

Step 3: Compute Maximum 1s

return totalOnes + maxGain;

Example Walkthrough

Input: [1, 0, 0, 1, 0]

  1. totalOnes = 2

  2. Gain array = [-1, 1, 1, -1, 1]

  3. Maximum subarray sum = 2 (indices 1-2)

  4. Maximum 1s = 2 + 2 = 4

Input: [1, 1]

  1. totalOnes = 2

  2. Gain array = [-1, -1]

  3. Maximum subarray sum = 0 (flipping decreases 1s)

  4. Maximum 1s = 2 + 0 = 2

Complexity Analysis

Conclusion

This approach efficiently finds the maximum number of 1s after flipping at most one subarray. Using Kadane’s Algorithm on a gain array is the key insight to solving it in linear time.