2023-08-06 Daily Challenge

Today I have done leetcode's August LeetCoding Challenge with cpp.

August LeetCoding Challenge 6

Description

Number of Music Playlists

Your music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that:

  • Every song is played at least once.
  • A song can only be played again only if k other songs have been played.

Given n, goal, and k, return the number of possible playlists that you can create. Since the answer can be very large, return it modulo 109 + 7.

 

Example 1:

Input: n = 3, goal = 3, k = 1
Output: 6
Explanation: There are 6 possible playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1].

Example 2:

Input: n = 2, goal = 3, k = 0
Output: 6
Explanation: There are 6 possible playlists: [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], and [1, 2, 2].

Example 3:

Input: n = 2, goal = 3, k = 1
Output: 2
Explanation: There are 2 possible playlists: [1, 2, 1] and [2, 1, 2].

 

Constraints:

  • 0 <= k < n <= goal <= 100

Solution

class Solution {
  using ll = long long;
  const int MOD = 1e9 + 7;
public:
  int numMusicPlaylists(int n, int goal, int k) {
    vector<vector<ll>> dp(2, vector<ll>(n + 1));
    dp[0][0] = 1;
    
    for(int i = 1; i <= goal; ++i) {
      int parity = i & 1;
      dp[parity][0] = 0;
      for(int j = 1; j <= min(i, n); ++j) {
        dp[parity][j] = dp[parity ^ 1][j - 1] * (n - j + 1);
        dp[parity][j] %= MOD;
        if(i > k) {
          dp[parity][j] += dp[parity ^ 1][j] * (j - k);
          dp[parity][j] %= MOD;
        }
      }
    }

    return dp[goal & 1][n];
  }
};

// Accepted
// 83/83 cases passed (3 ms)
// Your runtime beats 83.78 % of cpp submissions
// Your memory usage beats 61.26 % of cpp submissions (6.3 MB)