kt: add «552. Student Attendance Record II»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-05-27 00:51:20 +02:00
parent 8157017f38
commit 0a97fc0356
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,43 @@
val MOD = 1000000007
class Solution {
private fun createState(): MutableList<MutableList<Int>> = (0..1).map { mutableListOf(0, 0, 0) }.toMutableList()
fun checkRecord(n: Int): Int {
val initialState = createState()
initialState[0][0] = 1
val finalState =
(1..n).fold(initialState) { state, _ ->
val nextState = createState()
(0..1).flatMap { absences -> (0..2).map { lates -> absences to lates } }.forEach { (absences, lates) ->
nextState[absences][0] = (nextState[absences][0] + state[absences][lates]) % MOD
if (absences < 1) {
nextState[absences + 1][0] = (nextState[absences + 1][0] + state[absences][lates]) % MOD
}
if (lates < 2) {
nextState[absences][lates + 1] = (nextState[absences][lates + 1] + state[absences][lates]) % MOD
}
}
return@fold nextState
}
return finalState.fold(0) { acc, it ->
it.fold(acc) { acc, it ->
(acc + it) % MOD
}
}
}
}
fun main() {
val s = Solution()
check(s.checkRecord(2) == 8)
check(s.checkRecord(1) == 3)
check(s.checkRecord(10101) == 183236316)
}