Input: n=2, l=1, r=3
Output: 3 1
Explanation: [1,2][2,1][3,3]
Input: n = 3, l = 2, r = 2
Output: 1
The intuition behind the solution is based on modular arithmetic and dynamic programming.
Here’s a detailed explanation:
Modular Arithmetic: Since we need the sum of the array to be divisible by 3, we don’t care about the actual numbers themselves, but their remainder when divided by 3. This means we’re interested in how many numbers x exists such that x mod 3 equals 0, 1, or 2. We can count these numbers using simple formulas. For example, to count the number of x with a remainder of 1 when divided by 3 (i.e., x = 3k + 1 for some integer k), we can create an inequality l ≤ 3k + 1 ≤ r, simplify it to ceil((l-1)/3) ≤ k ≤ floor((r-1)/3), and then count the number of such k.
Dynamic Programming: After counting all the numbers, we can solve the problem using dynamic programming. We define dp[i][j] as the number of ways to form an array with i numbers such that the sum of these numbers modulo 3 equals j. There are O(n) states (since i can range from 0 to n and j can range from 0 to 2), and we can transition between states by adding a number to the array. The final answer will be at dp[n][0], which represents the number of ways to form an array of length n such that the sum of the numbers is divisible by 3.
The recurrence relation is:
dp[i][(j + k) % 3] = (dp[i][(j + k) % 3] + dp[i - 1][j] * cnt[k]) % MOD
This recurrence relation is used to fill the dynamic programming table dp. Here’s what it represents:
- dp[i][(j + k) % 3] is the current state, representing the number of arrays of length i where the sum of the elements has a remainder of (j + k) % 3 when divided by 3.
- dp[i][(j + k) % 3] is updated by adding the number of arrays of length i - 1 where the sum of the elements has a remainder of j when divided by 3, multiplied by the count of numbers that have a remainder of k when divided by 3 (cnt[k]).