HardArrayDynamic Programming

Dice Roll Simulation

1 approach, code in every language

Problem description

A six-sided die shows faces 1 through 6. You are given an integer n and an array rollMax of length 6, where rollMax[i] is the maximum number of times the face (i + 1) is allowed to appear consecutively.

You roll the die exactly n times, producing a sequence of faces. A sequence is valid only if no face ever appears more than its allowed number of consecutive repetitions. Count the number of distinct valid sequences of length n. Because the count can be very large, return it modulo 10^9 + 7.

Example 1

Input: n = 2, rollMax = [1,1,2,2,2,3]

Output: 34

There are 36 sequences of length two. Face 1 and face 2 may each appear at most once in a row, so the pairs (1,1) and (2,2) are forbidden. Removing those two invalid sequences leaves 34.

Example 2

Input: n = 2, rollMax = [1,1,1,1,1,1]

Output: 30

No face may repeat consecutively, so all six doubles are forbidden. That leaves 36 - 6 = 30 valid sequences.

Constraints

  • 1 <= n <= 5000
  • rollMax.length == 6
  • 1 <= rollMax[i] <= 15

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free