- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 38 lines of Java from the credited upstream file 3405.java.
- The implementation visibly relies on sequence storage.
- 1 loop block detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int countGoodArrays(int n, int m, int k) {3 final long[][] factAndInvFact = getFactAndInvFact(n);4 final long[] fact = factAndInvFact[0];5 final long[] invFact = factAndInvFact[1];6 return (int) (m * modPow(m - 1, n - k - 1) % MOD * nCk(n - 1, k, fact, invFact) % MOD);7 }8 9 private static final int MOD = 1_000_000_007;10 11 private long modPow(long x, long n) {12 if (n == 0)13 return 1;14 if (n % 2 == 1)15 return x * modPow(x, n - 1) % MOD;16 return modPow(x * x % MOD, n / 2);17 }18 19 private long[][] getFactAndInvFact(int n) {20 long[] fact = new long[n + 1];21 long[] invFact = new long[n + 1];22 long[] inv = new long[n + 1];23 fact[0] = invFact[0] = 1;24 inv[0] = inv[1] = 1;25 for (int i = 1; i <= n; ++i) {26 if (i >= 2)27 inv[i] = MOD - MOD / i * inv[MOD % i] % MOD;28 fact[i] = fact[i - 1] * i % MOD;29 invFact[i] = invFact[i - 1] * inv[i] % MOD;30 }31 return new long[][] {fact, invFact};32 }33 34 private int nCk(int n, int k, long[] fact, long[] invFact) {35 return (int) (fact[n] * invFact[k] % MOD * invFact[n - k] % MOD);36 }37}38