Maximum Continuous Sequence - C++ Solution

1. Introduction

The "Maximum Continuous Sequence" problem is a variation of array manipulation challenges, where the goal is to maximize the length of a continuous sequence of 1s by replacing only one 0 in a binary array. This problem tests understanding of array traversal and maintaining state during iteration.

Problem

Given a binary array, the task is to find the index of a 0 that should be replaced with a 1 to create the longest sequence of continuous 1s. If the array contains only 1s, return -1. If there are multiple indices where the replacement yields the maximum length, return the index of the first occurrence.

2. Solution Steps

1. Use two pointers to traverse the array: start and end.

2. Maintain a count of zeroes encountered.

3. When more than one zero is found, increment start until the count of zeroes is one.

4. Update the length of the longest sequence and the index of the first 0 in the current window.

5. Continue this process for the entire array.

3. Code Program

#include <iostream>
#include <vector>
using namespace std;

// Function to find the index to be replaced to get the longest sequence of continuous 1s
int findIndexOfZero(vector<int>& nums) {
    int maxCount = 0, maxIndex = -1;
    int start = 0, zeroCount = 0;

    for (int end = 0; end < nums.size(); end++) {
        if (nums[end] == 0) {
            zeroCount++;
        }

        // If there are more than one zero in the current window, move start forward
        while (zeroCount > 1) {
            if (nums[start] == 0) {
                zeroCount--;
            }
            start++;
        }

        // Update maximum length and index of the first zero
        if (end - start + 1 > maxCount) {
            maxCount = end - start + 1;
            maxIndex = start;
        }
    }

    // Check for all 1's in the array
    return maxIndex == -1 || zeroCount == 0 ? -1 : maxIndex;
}

int main() {
    vector<int> nums = {0, 0, 1, 0, 1, 1, 1, 0, 1, 1};
    cout << findIndexOfZero(nums) << endl;
    return 0;
}

Output:

7

Explanation:

The program finds the index of 0 to be replaced by maintaining a window with at most one zero. 

It traverses the array with two pointers, start and end, updating the window size and the first zero index when a longer sequence is found. 

If the count of zeroes exceeds one, the start pointer is moved forward to maintain only one zero in the window. 

The algorithm effectively finds the optimal index to replace, ensuring the longest continuous sequence of 1s, and handles edge cases like all 1s in the array.


Comments