# [J], 29 bytes

    0{(,~#|1+}.i.{.)@]^:(>#)^:_&0

[Try it online!][TIO-jwqxaile]

[J]: http://jsoftware.com/
[TIO-jwqxaile]: https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Dao1dOqUawy1a/Uy9ar1NB1i46w07JQ146zi1Qz@a3KlJmfkA5XbKqQpGEI4RmCOBYRjCpGxhPAswTwjcwjPBKLS1AjZEDOT/wA "J – Try It Online"