下面有没有更优雅的方法来实现这个:
输入:
array = [1, 1, 1, 0, 0, 1, 1, 1, 1, 0]
输出:
4
我的算法:
streak = 0
max_streak = 0
arr.each do |n|
if n == 1
streak += 1
else
max_streak = streak if streak > max_streak
streak = 0
end
end
puts max_streak
最佳答案
类似于w0lf's answer , 但通过从 chunk
返回 nil
来跳过元素:
array.chunk { |x| x == 1 || nil }.map { |_, x| x.size }.max
关于ruby - 获取数组中值的最大连续出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29700939/