Task description
You are given a list and an item, find the length of the longest consecutive subsequence of the list containing only the item.
Testcases
[1, 1, 2, 3] 1 -> 2
[1, 0, 0, 2, 3, 0, 4, 0, 0, 0, 6] 0 -> 3
This code is pretty readable in my opinion but I fear that the \$O(N^2)\$ time complexity is sub-optimal.
def subsequences(arr)
((0...arr.length).to_a)
.repeated_permutation(2)
.select {|start, finish| finish >= start}
.collect {|start, finish| arr[start..finish] }
end
def longest_item_only_subsequence_len(arr, item)
subsequences(arr)
.select {|seq| seq.all? {|i| i == item} }
.max_by(&:length)
.length
end
p subsequences([1, 2, 3])
p longest_item_only_subsequence_len([1, 0, 0, 2, 3, 0, 4, 0, 0, 0, 6], 0)