HardArrayDynamic Programming

Dice Roll Simulation

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now