Given an array A. Find maximum length of sub-array with product of its elements being non zero.
EXPLANATION
Product of a sub-array will be zero if and only if it contains at least one zero element.
So we have to find out maximum size of the sub-array not containing zero.
So we can start processing the array from left to right and keep track of last position where we had found the zero element, at each step
we will compute the maximum size of the sub-array ending at the current position and not having any zeros in it (For i th element, the size of the sub-array will
be i - lastZeroIndex where lastZeroIndex is the index of the last zero found).
Finally we will take the maximum of all those values for each index i from 1 to N.
Please see the simple pseudo code.
lastZeroIndex = 0, ans = 0
for i = 1 to N:
if a[i] == 0:
lastZeroIndex = i
cur = i - lastZeroIndex
ans = max(ans, cur)
Complexity:
O(N), You just need a single pass of the array a.
int main()
{
unsigned long long int N, a[max], i, j = 1;
unsigned long long int maxim = 0, maxfin = 0;
cin >> N;
for(i = 0; i < N; i++)
cin >> a[i];
for(i = 0; i < N && j < N;)
{
if(a[i] != 0)
maxim++;
while(a[i]*a[j] != 0)
{
j++;
maxim++;
}
i = j + 1;
j = i + 1;
if(maxim > maxfin)
maxfin = maxim;
maxim = 0;
}
cout << maxfin;
}
Although this approach is different from the one in the editorial....i always got wrong answer...please help?
your solution is wrong for some inputs where N = 1… since j is always starting at 1…
it will not enter the for loop and the maxfin will remain equals to 0… the answer for all N = 1 is 1 if a[0] != 0…
Well this solution can be optimized more in terms of space requirement by not taking the array. Instead take an element one by one and increment the count. If the input turns out to be zero then set count equal to zero
The code can be