# [Jelly], 12 bytes

    Dd4d2FṙRḄṢIS

Too slow and memory hungry for the last two test cases. This could be fixed, at the cost of a byte, by replacing `ṙR` with `ṙJ$`.

[Try it online!][TIO-ja1vln9z]

[Jelly]: https://github.com/DennisMitchell/jelly
[TIO-ja1vln9z]: https://tio.run/##y0rNyan8/98lxSTFyO3hzplBD3e0PNy5yDP4/9E9h9sfNa1x///fyNhER8EQSuooWJqbWhgbAgA "Jelly – Try It Online"