1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-16 16:36:56 +02:00
LeetCode/kt/student-attendance-record-ii.kt
Matej Focko 0a97fc0356
kt: add «552. Student Attendance Record II»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-05-27 00:51:20 +02:00

43 lines
1.3 KiB
Kotlin

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)
}