The logic is that, after the cell is 12 or 13, 6 rows should be filtered, until it finds another 12 or a 13. if the number of rows are under 6 till it finds 12 or 13, the maximum numbers possible should be filtered.
Hope this makes sense.
Attached the input and output for your convenience.