![]() |
VOOZH | about |
Given N playing cards, the task is to return the number of distinct house of cards we can build using all N cards. A house of cards meets the following conditions:
Note: Two houses of cards are considered distinct if there exists a row where the two houses contain a different number of cards.
Examples:
Input: N = 2
Output: 1
Explanation: Only one house of cards having 1 row can be built using 2 cards.Input: N = 16
Output: 2
Explanation: The two valid houses of cards are shown.
The third house of cards in the diagram is not valid because the rightmost triangle on the top row is not placed on top of a horizontal card.
Approach: To solve the problem, follow the below idea:
The problem can be solved using Dynamic Programming. Maintain a recursive function solve(n, prevTriangles) which returns the number of possible houses if we have n cards and the previous row had prevTriangles. In each row, we know that the first triangle will need 2 cards and every subsequent triangle will need 3 cards. Now in every row, start making triangles one by one and after making each triangle, move to the next row with the remaining cards. At any point, if we reach a row with 0 cards, then we have constructed a valid house so increment ans by 1. After all the recursive calls, return ans.
The above recursive calls can be momoized using a dp[][] table such that dp[i][j] stores the number of ways to construct a valid house using i cards such that the previous row had j triangles.
Below is the implementation of the above algorithm:
2
Time Complexity: O(N*N), where N is the total number of cards.
Auxiliary Space: O(N * N)