Max Consecutive Ones III in C++

C++Server Side ProgrammingProgramming

Suppose we have an array A of 0s and 1s, we can update up to K values from 0 to 1. We have to find the length of the longest (contiguous) subarray that contains only 1s. So if A = [1,1,1,0,0,0,1,1,1,1,0] and k = 2, then the output will be 6, So if we flip 2 0s, the array can be of like [1,1,1,0,0,1,1,1,1,1,1], the length of longest sequence of 1s is 6.

To solve this, we will follow these steps −

  • set ans := 0, j := 0 and n := size of array
  • for i in range 0 to n – 1
    • if A[i] is 0, then decrease k by 1
    • while j <= i and k < 0
      • if A[j] = 0, then increase k by 1
      • increase j by 1
    • ans := max of i – j + 1, ans
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int longestOnes(vector<int>& A, int k) {
      int ans = 0;
      int j = 0;
      int n = A.size();
      for(int i = 0; i < n; i++){
         if(A[i] == 0) k--;
         while(j <= i && k <0){
            if(A[j] == 0){
               k++;
            }
            j++;
         }
         ans = max(i - j + 1, ans);
      }
      return ans;
   }
};
main(){
   vector<int> v = {1,1,1,0,0,0,1,1,1,1,0};
   Solution ob;
   cout <<(ob.longestOnes(v, 3));
}

Input

[1,1,1,0,0,0,1,1,1,1,0]
3

Output

10
raja
Published on 30-Apr-2020 11:14:48
Advertisements