educative.io

Educative

My C++ solution

using namespace std;

#include

#include

class ReplacingOnes {

public:

static int findLength(const vector& arr, int k) {

int  maxLength = 0;

int number_of_ones = 0;

int left = 0;

for(int right = 0; right < arr.size(); ++right)

{

    number_of_ones += arr.at(right);

    if(right-left > number_of_ones + k)

    {

        number_of_ones -= arr.at(left);

        ++left;

    }

    maxLength = max(maxLength, number_of_ones + k);

}

// TODO: Write your code here

return maxLength;

}

};

Hi @Petr_Tomicek, we are glad you reached us.

Your c++ solution is right . For your convenience, below is the complete code with your c++ function and a little fit of alterations that I did to make the code functional.

#include
using namespace std;

int longestSubSeg(int arr[],int size, int k) {

int maxLength = 0;

int number_of_ones = 0;

int left = 0;

for(int right = 0; right < size; ++right)

{

number_of_ones += arr[right];

if(right-left > number_of_ones + k)

{

    number_of_ones -= arr[left];

    ++left;

}

maxLength = max(maxLength, number_of_ones + k);

}

// TODO: Write your code here

return maxLength;
}
// Driver code
int main()
{
int a[] = { 1, 0, 0, 1, 0, 1, 0, 1 };
int k = 2;
int n = sizeof(a) / sizeof(a[0]);
cout << longestSubSeg(a,n, k);
return 0;
}

I hope Educative has helped you in your learning experience :slight_smile: