He said that out of irony...
Jesus never said He wasn't good. The rich young ruler approached Jesus and addressed Him as, "Good Teacher". Jesus replied, "Why do you call me good, there is none good but God."
What Jesus did was basically to challenge the man to make a decision about who Jesus was.
There are only two ways to take that verse. Either Jesus was claiming to be God. Or Jesus really meant that He wasn't good. But if Jesus wasn't good, then He wasn't a fit sacrifice for our sins. He would be in need of a Savior Himself.
He said it out of humility.