Given two natural number n and m. The task is to find the number of ways in which the numbers that are greater than or equal to m can be added to get the sum n.
Input : n = 3, m = 1 Output : 3 Following are three different ways to get sum n such that each term is greater than or equal to m 1 + 1 + 1, 1 + 2, 3 Input : n = 2, m = 1 Output : 2 Two ways are 1 + 1 and 2
The idea is to use Dynamic Programming by define 2D matrix, say dp. dp[i][j] define the number of ways to get sum i using the numbers greater than or equal to j. So dp[i][j] can be defined as:
If i < j, dp[i][j] = 0, because we cannot achieve smaller sum of i using numbers greater than or equal to j.
If i = j, dp[i][j] = 1, because there is only one way to show sum i using number i which is equal to j.
Else dp[i][j] = dp[i][j+1] + dp[i-j][j], because obtaining a sum i using numbers greater than or equal to j is equal to the sum of obtaining a sum of i using numbers greater than or equal to j+1 and obtaining the sum of i-j using numbers greater than or equal to j.
Below is the implementation of this approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Number of ways to select equal sized subarrays from two arrays having atleast K equal pairs of elements
- Number of ways to divide an array into K equal sum sub-arrays
- Count number of binary strings such that there is no substring of length greater than or equal to 3 with all 1's
- Number of ways of choosing K equal substrings of any length for every query
- Count ways to partition a string such that both parts have equal distinct characters
- Ways of filling matrix such that product of all rows and all columns are equal to unity
- Number of ways to obtain each numbers in range [1, b+c] by adding any two numbers in range [a, b] and [b, c]
- Number of ways to get even sum by choosing three numbers from 1 to N
- Number of ways to split N as sum of K numbers from the given range
- Count number of ways to arrange first N numbers
- Bell Numbers (Number of ways to Partition a Set)
- Number of ways to arrange N numbers which are in a range from 1 to K under given constraints.
- Calculate Stirling numbers which represents the number of ways to arrange r objects around n different circles
- Count numbers whose difference with N is equal to XOR with N
- Count numbers (smaller than or equal to N) with given digit sum
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.