Greedy O(n) solution. Simple approach but a little lengthy code


#1
public class Solution {
    public int solve(int[] A, int B) {
        int ct=0;

        //check for front missing light
        for(int i=0;i<A.length;i++){
            if(A[i]==0) ct++;
            else break;
            if(ct==B) return -1;
        }
        ct=0;

        //check for end missing light
        for(int i=A.length-1;i>=0;i--){
            if(A[i]==0) ct++;
            else break;
            if(ct==B) return -1;
        }
        ct=0;int fl_ct=0,fl=-1;

        //check for middle missing light and first ON light
        for(int i=0;i<A.length;i++){
            fl_ct++;
            if(A[i]==1 && fl_ct<=B) fl=i;
            if(A[i]==0) ct++;
            else ct=0;
            if(ct==2*B-1) return -1;
        }

        //checking for the next light to ON after first ON light
        int ans=1,nl=-1,curr=-1;
        ct=0;
        for(int i=fl+1;i<A.length;i++){
            ct++;
            if(A[i]==1) curr=i;
            if(ct==2*B-1){
                nl=curr;
                ct=i-curr;
                curr=-1;
                ans++;
            }
        }

        
        if(curr!=-1 && ct>=B) ans++;
        return ans;
    }
}