a goog non-dp solution.
9Z's DP solution added.
learned from 9Z.