Chef And Subarray - CHEFZOT CodeChef Easy Question

Hello everyone !

 

Welcome back to my blog , today we will be discussing a straightfoward question .
You just need to compute the largest contiguous subarray with non-zero product.
Here is a link to the PROBLEM

Prerequisites to solve this problem - None 

Solution - Just start from the first index and then continue counting till you get a zero , take a max variable and then start counting again .
Whenever you encounter a zero , check if count is greater than max , if it is update max else continue .

In the end max would have the answer.

Take a look at the following C++ code to understand the solution better :-

#include <iostream>
using namespace std;

int main() {
    long int n;
    cin>>n;
    long int arr[n];
    long int i=0;
    int x;
    while(i!=n)
    {
        cin>>arr[i];
        i++;
    }
    int ans=0;
    long int max=0,count=0;
    i=0;
    while(i!=n)
    {
        if(arr[i]==0)
        {
            if(count>max)
            {
                max=count;
            }
            count=0;
            
        }
        else
        {
            count++;
        }
        i++;
        
    }
    if(max<count)
    max=count;
    cout<<max<<endl;
    
// your code goes here
return 0;
}


Please leave your doubts and queries in the comments section .


Comments

Popular Posts