For completeness’ sake I’m also posting Python Mode & p5.js flavors of my original Java Mode version:
"""
* Max Number of Consecutive Non-Zero Values (v1.0.1)
* GoToLoop (2021/Apr/08)
*
* https://Discourse.Processing.org/t/
* how-do-i-find-a-maximum-number-of-
* consecutive-non-zero-values-in-the-array/29200/21
"""
vals = (
0, # 0
MAX_INT, MIN_INT, 0, # 2
-1, 3, 40, 100, 0, # 4
5 # 1
)
def setup():
print vals
print maxSeqNonZero(vals) # 4
exit()
def maxSeqNonZero(lst):
if not lst: return 0
seqCount = maxCount = 0
for n in lst:
seqCount += 1 if n else -seqCount
maxCount = max(maxCount, seqCount)
return maxCount
/**
* Max Number of Consecutive Non-Zero Values (v1.0.1)
* GoToLoop (2021/Apr/08)
*
* https://Discourse.Processing.org/t/
* how-do-i-find-a-maximum-number-of-
* consecutive-non-zero-values-in-the-array/29200/21
*/
const
MAX_INT = 2 ** 31 - 1,
MIN_INT = 2 ** 31 | 0,
vals = Int32Array.of(
0, // 0
MAX_INT, MIN_INT, 0, // 2
-1, 3, 40, 100, 0, // 4
5 // 1
);
function setup() {
noCanvas();
console.table(vals);
print(maxSeqNonZero(vals)); // 4
}
function maxSeqNonZero(arr) {
if (!arr || !arr.length) return 0;
var seqCount = 0, maxCount = 0;
for (const n of arr)
maxCount = max(maxCount, seqCount += n? 1 : -seqCount);
return maxCount;
}