Number of Music Playlists in C++

C++Server Side ProgrammingProgramming

Suppose we have a music player, that contains N different songs and we want to listen to L songs during our trip. So we have to make a playlist so that it meets these conditions −

  • Every song is played at least once

  • A song can only be played again only if K other songs have been played.

We have to find the number of possible playlists. The answer can be very large, so we will return it modulo 10^9 + 7.

So, if the input is like N = 2, L = 3, K = 0, then the output will be 6, as there are 6 possible playlists [1,1,2], [1,2,1], [2,1,1], [2,2,1], [2,1,2], [1,2,2].

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

  • Define a function sub(), this will take a, b,

  • return ((a mod m) - (b mod m) + m) mod m

  • Define a function mul(), this will take a, b,

  • return ((a mod m) * (b mod m)) mod m

  • From the main method, do the following −

  • Make one 2d array of size dp(L + 1) x (N + 1)

  • dp[0, 0] := 1

  • for initialize i := 1, when i <= L, update (increase i by 1), do −

    • for initialize j := 1, when j <= N, update (increase j by 1), do −

      • dp[i, j] := mul(dp[i - 1, j - 1], (N - (j - 1)))

      • if j > K, then −

        • dp[i, j] := add(dp[i, j], mul(dp[i - 1, j], j - K))

  • return dp[L, N]

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
const int m = 1e9 + 7;
typedef long long int lli;
class Solution {
   public:
   int add(lli a, lli b){
      return ((a % m) + (b % m)) % m;
   }
   int sub(lli a, lli b){
      return ((a % m) - (b % m) + m) % m;
   }
   int mul(lli a, lli b){
      return ((a % m) * (b % m)) % m;
   }
   int numMusicPlaylists(int N, int L, int K) {
      vector < vector <int> > dp(L + 1, vector <int>(N + 1));
      dp[0][0] = 1;
      for(int i = 1; i <= L; i++){
         for(int j = 1; j <= N; j++){
            dp[i][j] = mul(dp[i - 1][j - 1], (N - (j - 1)));
            if(j > K){
               dp[i][j] = add(dp[i][j], mul(dp[i - 1][j], j -
               K));
            }
         }
      }
      return dp[L][N];
   }
};
main(){
   Solution ob;
   cout << (ob.numMusicPlaylists(2, 3, 0));
}

Input

2,3,0

Output

6
raja
Published on 04-Jun-2020 09:06:24
Advertisements