Student Attendance Record II in C++


Suppose we have a positive integer n, we have to find the number of all possible attendance records with length n, which will be regarded as rewardable. As the answer may be very large, we will return it using mod 109 + 7.

In the student attendance record the string can only contain the following three characters −

  • 'A' means absent.
  • 'L' means late.
  • 'P' means present.

one attendance is treated as rewardable if it doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late). So we have to find the maximum points.

If the input is like 2, then the output will be 8, as we can generate 8 possible ways that can be rewarded, these are [PP, AP, PA, LP, PL, AL, LA, LL], only AA will not be there.

To solve this, we will follow these steps −

  • Define a function add(), this will take a, b,
    • return ((a mod m) + (b mod m)) mod m
  • From the main method, do the following,
  • Define an array p of size n + 1, array a of size n + 1, an array l of size n + 1, an array ap of size n + 1 and an array al of size n + 1
  • if n is same as 1, then −
    • return 3
  • p[0] := 1, p[1] := 1, p[2] := 3
  • a[0] := 1, a[1] := 1, a[2] := 2
  • l[0] := 1, l[1] := 1, l[2] := 3
  • ap[0] := 1, ap[1] := 1, ap[2] := 2
  • al[0] := 1, al[1] := 1, al[2] := 2
  • for initialize i := 3, when i <= n, update (increase i by 1), do −
    • p[i] := add(add(p[i - 1], a[i - 1]), l[i - 1])
    • l[i] := add(add(p[i - 1], p[i - 2]), add(a[i - 1], a[i - 2]))
    • a[i] := add(al[i - 1], ap[i - 1])
    • al[i] := add(ap[i - 1], ap[i - 2])
    • ap[i] := add(ap[i - 1], al[i - 1])
  • return add(add(p[n], l[n]), a[n])

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
const lli m = 1e9 + 7;
class Solution {
public:
   lli add(lli a, lli b){
      return ( (a % m) + (b % m) ) % m;
   }
   int checkRecord(int n) {
      vector <int> p(n+1), a(n+1), l(n+1), ap(n+1), al(n+1);
      if(n == 1)return 3;
      p[0] = 1;
      p[1] = 1;
      p[2] = 3;
      a[0] = 1;
      a[1] = 1;
      a[2] = 2;
      l[0] = 1;
      l[1] = 1;
      l[2] = 3;
      ap[0] = 1;
      ap[1] = 1;
      ap[2] = 2;
      al[0] = 1;
      al[1] = 1;
      al[2] = 2;
      for(int i = 3; i <= n; i++){
         p[i] = add(add(p[i-1], a[i-1]), l[i-1]);
         l[i] = add(add(p[i-1], p[i-2]),add(a[i-1] , a[i-2]));
         a[i] = add(al[i-1], ap[i-1]);
         al[i] = add(ap[i-1], ap[i-2]);
         ap[i] = add(ap[i-1], al[i-1]);
      }
      return add(add(p[n], l[n]), a[n]);
   }
};
main(){
   Solution ob;
   cout << (ob.checkRecord(3));
}

Input

3

Output

19

Updated on: 01-Jun-2020

410 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements