552. Student Attendance Record II #162
-
Topics: An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
Any student is eligible for an attendance award if they meet both of the following criteria:
Given an integer Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a dynamic programming approach. Given the constraints, especially the high value for Here's a step-by-step solution approach: Solution Approach
Let's implement this solution in PHP: 552. Student Attendance Record II <?php
/**
* @param Integer $n
* @return Integer
*/
function countValidAttendanceRecords($n) {
$kMod = 1000000007;
// Initialize DP arrays
$dp = array(array(0, 0, 0), array(0, 0, 0));
$dp[0][0] = 1; // Only one way to have an empty record
while ($n-- > 0) {
$prev = array_map(function($A) {
return array_values($A);
}, $dp);
$dp[0][0] = ($prev[0][0] + $prev[0][1] + $prev[0][2]) % $kMod;
$dp[0][1] = $prev[0][0];
$dp[0][2] = $prev[0][1];
$dp[1][0] = ($prev[0][0] + $prev[0][1] + $prev[0][2] + $prev[1][0] + $prev[1][1] + $prev[1][2]) % $kMod;
$dp[1][1] = $prev[1][0];
$dp[1][2] = $prev[1][1];
}
return (int)(($dp[0][0] + $dp[0][1] + $dp[0][2] + $dp[1][0] + $dp[1][1] + $dp[1][2]) % $kMod);
}
// Example usage
echo countValidRecords(2) . "\n"; // Output: 8
echo countValidRecords(1) . "\n"; // Output: 3
echo countValidRecords(10101) . "\n"; // Output: 183236316
?> Explanation:
This approach efficiently handles the problem using dynamic programming, considering the constraints and ensuring modular arithmetic to manage large numbers. |
Beta Was this translation helpful? Give feedback.
We can use a dynamic programming approach. Given the constraints, especially the high value for
n
, an efficient solution is required.Here's a step-by-step solution approach:
Solution Approach
Define the State Variables:
We use dynamic programming to keep track of the number of valid records based on:
Let:
dp[i][0][0]
be the number of valid records of lengthi
with 0 absences and no late days.dp[i][0][1]
be the number of valid records of lengthi
with 0 absences and 1 late day.dp[i][0][2]
be the number of valid records of lengthi
with 0 absences and 2 consecutive late days.dp[i][1][0]
be the number of valid records of lengthi
wi…