3916. Number of ZigZag Arrays III
MathDynamic ProgrammingPrefix Sum
Hints
Hint 1
Let
m = r - l + 1. The actual values do not matter, only how many distinct choices you have.Hint 2
The answer as a function of
m is a polynomial of degree at most n. So instead of working up to large m, compute values for small m.Hint 3
Use Dynamic Programming:
dp[i][j][dir] = number of arrays of length i ending at value j with last move direction dir (up/down). Use prefix sums to transition in O(n^2) total for all m <= n+1.Hint 4
After computing answers for
m = 1, 2, ..., n+1, use Lagrange interpolation to evaluate the polynomial at the actual m in O(n) or O(n^2) time.Preparing judge…