920. Number of Music Playlists

Explanation

To solve this problem, we can use dynamic programming. We can define a dp array where dp[i][j] represents the number of playlists of length i using j different songs. We can then iteratively fill in the dp array by considering the number of ways to choose the next song to add to the playlist.

At each step, we have two choices:

  1. If we have not yet reached the goal number of songs, we can add a new song to the playlist. This can be done in (n - j) ways.
  2. If we have reached the goal number of songs, we can choose from the songs that have already been played, but we need to ensure that no song repeats until k other songs have been played. This can be done in max(0, j - k) ways.

The final answer is stored in dp[goal][n].

Time complexity: O(n * goal) Space complexity: O(n * goal)

class Solution {
    public int numMusicPlaylists(int n, int goal, int k) {
        int mod = 1000000007;
        long[][] dp = new long[goal + 1][n + 1];
        dp[0][0] = 1;

        for (int i = 1; i <= goal; i++) {
            for (int j = 1; j <= n; j++) {
                dp[i][j] += dp[i - 1][j - 1] * (n - j + 1);
                dp[i][j] += dp[i - 1][j] * Math.max(0, j - k);
                dp[i][j] %= mod;
            }
        }

        return (int) dp[goal][n];
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.