
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.
1#include <iostream>
2#include <vector>
3#define MOD 1000000007
4
5int checkRecord(int n) {
6 std::vector<std::vector<std::vector<int>>> dp(2, std::vector<std::vector<int>>(n, std::vector<int>(3, 0)));
7 dp[0][0][0] = 1;
8 for (int i = 0; i < n; i++) {
9 for (int a = 0; a <= 1; a++) {
10 for (int l = 0; l < 3; l++) {
11 if (i < n - 1) {
12 dp[a][i + 1][0] = (dp[a][i + 1][0] + dp[a][i][l]) % MOD;
13 if (a == 0)
14 dp[1][i + 1][0] = (dp[1][i + 1][0] + dp[a][i][l]) % MOD;
15 if (l < 2)
16 dp[a][i + 1][l + 1] = (dp[a][i + 1][l + 1] + dp[a][i][l]) % MOD;
17 }
18 }
19 }
20 }
21 int res = 0;
22 for (int a = 0; a <= 1; a++) {
23 for (int l = 0; l < 3; l++) {
24 res = (res + dp[a][n - 1][l]) % MOD;
25 }
26 }
27 return res;
28}
29
30int main() {
31 int n = 2;
32 std::cout << checkRecord(n) << std::endl;
33 return 0;
34}The C++ solution uses a 3D dynamic programming table, where dp[a][i][l] denotes the count of sequences of length i with a 'A's and ending with l 'L's, iteratively calculating valid sequences.
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.
1
The C code uses matrix exponentiation to compute the count of valid sequences. The matrices model possible state transitions, and raising the transition matrix to the nth power efficiently computes the number of valid sequences.