Koa and the Beach (Hard Version)

CodeForces - 1384B2