Define a matrix $M$ of size $n \times W \times L$. The entry $M[i][j][k]$ denotes the maximum value of the knapsack when exactly $k$ items are chosen from $\{1,\dotsc,i\}$ and the allowed capacity of the knapsack is $j$.
Final Solution: The value of $M[n][W][L]$ (assuming 1 based indexing).
Induction or DP: $M[i][j][k]$ can be stated in terms of smaller subproblem as follows: $M[i][j][k] = \max\,\{\,M[i-1][j-w_i][k-1] + v_i, \, M[i-1][j][k]\}$.
The first term denotes the scenario when the $i^{th}$ item is chosen in the knapsack, and the second term states the scenario when the $i^{th}$ item is not chosen in the knapsack.
Base Case:
- For any entry with $k > i$, $M[i][j][k] = -\infty$ since there are only $i$ available items and the desired quantity is $k$.
- For every $j \in \{1,\dotsc,W\}$, $i \in \{1,\dotsc,n\}$, and $k = i$, the value $M[i][j][i] = \sum_{p = 1}^{i} v_p$ if $\sum_{p = 1}^i w_p \leq j$ else $M[p][j][p] = -\infty$. In other words, if there are only $i$ available items and the required quantity is also $i$, then pick all the items in the knapsack if and only if the items satisfy the capacity constraint, i.e., sum of weights of the items is at most $j$.
Running Time: $O(W\cdot L \cdot n)$