One element only subarray max length 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 -&gt; 2
[1, 0, 0, 2, 3, 0, 4, 0, 0, 0, 6] 0 -&gt; 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 &gt;= 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(&amp;: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)
Yes, chunk is the way to go. I'd write it differently, though, using a list-comphehension approach (in Ruby: map+if+compact. Or with a custom method.) and taking in account the edge case (no elements item in the array):

def longest_item_only_subsequence_len(xs, item)
  xs.chunk(&amp;:itself).map { |y, ys| ys.size if y == item }.compact.max || 0
end