precalculate with dp, there is better algorithm with math