Do anyone know its dp solution?

It can be done but would be an overkill.
https://ideone.com/9sPWqn