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

Thanks, @solub. Python is great!

Another Python solution:

def maxNonZeroSequence(nums):
  return max(len(s) for s in ("".join(["0" if n == 0 else "1" for n in nums])).split("0"))

EDIT (2x on April 8, 2021):

So as to provide @batmm with something useful that can easily be converted to Java, here’s a p5.js solution:

function maximumConsecutiveNonZero(nums) {
  let ct = 0; 
  let mx = 0; 
  for (let i = 0; i < nums.length; i += 1) { 
    if (nums[i] == 0) {
      ct = 0;
    } else { 
      ct += 1;
      if (ct > mx) { 
        mx = ct; 
      } 
    }
  }
  return mx;
}
2 Likes