for example if we consider the case for 3 places with numbers from [1..3]..we can do it in 5 ways:
1 1 1
1 1 2
1 2 1
1 2 2
1 2 3
In second place we cant have 3 as the difference between 2nd and 1 first place will be more than 1.
Any place (say i ) can have value atmost 1 more than the LARGEST value at its previous positions (i.e from 1 ..i-1)
Let
dp[i, j] = how many possibilities of generating i positions such that the max is j, following the restrictions.We have:
(1): We have the max
jfor the firsti - 1elements already, so we can put anything on positionias long as this doesn’t break the rule. This anything is clearly:1, ..., j.(2): We don’t have the max
jfor the firsti - 1, so we must make it so, by appendingjto all those with a max ofj - 1. Note that if the max of1 ... i - 1is< j - 1, we cannot make the max of1 ... ito bejwhile following the restrictions of the problem, so there is no point considering anydp[i - 1, k < j - 1].This can be implemented in
O(n^2), which should be fast enough for fornup to about 5000 on a decent CPU. The memory used is alsoO(n^2).