# [Haskell], 212 bytes This is probably way too long, but it finally works now. (Thanks to @Lynn for the [cartesian product trick](https://codegolf.stackexchange.com/a/52945/24877)!) <!-- language-all: lang-hs --> import Data.List b%l=[l++[x|b/=last l,x`notElem`l,1==sum[1|(u,v)<-x`zip`last l,u/=v]]|x<-mapM id[[1>0,1<0]|_<-b]] b!a|f<-nub.concat.((b%)<$>)=snd$maximum$map(length>>=(,))$filter((==b).last)$until(f>>=(==))f[[a]] [Try it online!][TIO-j87w317a] [Haskell]: https://www.haskell.org/ [TIO-j87w317a]: https://tio.run/##dZAxb8MgEIV3/4qr5Mig2E68G09tp3RqN4RqSHCMCtgykLqV/7tL1FSZOnBP4rt3j6Pn7kNqva7KjMPk4ZF7Xh6U84nYaEL1dkvnReyI5s6DzufWDv5JS9PqvCLEBUOrBYX8gutibr/V2N4aw45cGFvmujB8fAF1orRq9nlV79nyXheCsUQ88KWrCxtEeRzskfsSIbHBddpg4uwpNXxWJpioI9LSnn3fNATlGKed0l5OCBEicHkNxGmwXmnUXTsIwbijlDO2ciBA36Ygc3jm2v1JzL6De2XJOEnvv2COVHVRfC8tZFUGMrog22eJ4cpGOgb/6qeDhRRcP3xGub4yHvgdgeNN3C8pCvjXETlEHj8U3HDzrT8 "Haskell – Try It Online"