How do I find a maximum number of consecutive non-zero values in the array?

Not as elegant as GoToLoop’s solution but another approach could consist in converting the original array to a single string, splitting it into sublists at "0" separators and getting the length of the longest one.

This is pretty straightforward in Python mode, but not sure that would translate easily in Java.

Example:

# For arrays of 0 and 1 only
s = [1,0,1,1,0,0,1,1,1,1,0,1]

print len(max(''.join(map(str,s)).split("0"))) # --> 4

# For any array of integers
s = [8,0,4,2,0,0,3,7,1,6,0,9]

print len(max(''.join(map(lambda x:str(int(x>0)),s)).split("0")))  # --> 4
2 Likes