
Sponsored
Sponsored
This approach leverages dynamic programming to count eligible attendance records. We define a function dp[i][a][l], which represents the number of valid sequences of length i with a absences and l consecutive lates. The transitions will account for adding 'P', 'A', or 'L' to existing records, ensuring we respect the problem's constraints.
Time complexity: O(n), Space complexity: O(1), as we use only a fixed amount of space irrespective of n.
Solve with full IDE support and test cases
The C solution uses a bottom-up dynamic programming approach with space optimization. Arrays l_dp track sequences ending in late days to limit space, and the solution iteratively calculates valid sequences of increasing length up to n.
This approach uses matrix exponentiation to efficiently solve the problem by leveraging the recursive relationship of the transformation matrices, which model the state transitions of the sequences. The matrix exponentiation technique drastically reduces the time complexity by harnessing fast exponentiation properties.
Time complexity: O(log n), Space complexity: O(1), because we only manipulate fixed-size arrays.
1using System;
2
3public class Solution {
4 private const int MOD = 1000000007;
5
6 private static int[][] Multiply(int[][] A, int[][] B) {
7 int size = A.Length;
8 var C = new int[size][];
9 for (int i = 0; i < size; ++i) {
10 C[i] = new int[size];
11 for (int j = 0; j < size; ++j) {
12 for (int k = 0; k < size; ++k) {
13 C[i][j] = (int)((C[i][j] + (long)A[i][k] * B[k][j]) % MOD);
14 }
15 }
16 }
17 return C;
18 }
19
20 private static int[][] Power(int[][] F, int n) {
21 int size = F.Length;
22 int[][] result = new int[size][];
23 for (int i = 0; i < size; i++) {
24 result[i] = new int[size];
25 result[i][i] = 1;
26 }
27 while (n > 0) {
28 if ((n & 1) == 1) result = Multiply(result, F);
29 F = Multiply(F, F);
30 n >>= 1;
31 }
32 return result;
33 }
34
35 public int CheckRecord(int n) {
36 if (n == 1) return 3;
37 int[][] F = {
38 new int[] {1, 1, 0, 1, 0, 0},
39 new int[] {1, 0, 1, 0, 0, 0},
40 new int[] {0, 1, 0, 0, 0, 0},
41 new int[] {0, 0, 0, 1, 1, 0},
42 new int[] {0, 0, 0, 0, 1, 1},
43 new int[] {0, 0, 0, 0, 0, 1}
44 };
45 var result = Power(F, n - 1);
46 return (int)((2 * result[0][0] + result[0][1] + result[0][3]) % MOD);
47 }
48
49 public static void Main() {
50 var solution = new Solution();
51 Console.WriteLine(solution.CheckRecord(2));
52 }
53}The C# solution efficiently reduces computation time through matrix operations for modeling state transitions, maintaining constant matrix sizes and leveraging exponentiation logic.