![]() |
VOOZH | about |
Given two natural numbers 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.
Examples:
Input: n = 3, m = 1
Output: 3
Explanation: Three different ways to get sum n such that each term is greater than or equal to m are 1 + 1 + 1, 1 + 2 and 3Input: n = 2, m = 1
Output: 2
Explanation: Two different ways to get sum n such that each term is greater than or equal to m are 1 + 1 and 2
Table of Content
The idea is to find the number of ways to reach n by trying each value of m from m to n. Starting from the target sum n, for each m, we can either include it or exclude it. If we include it, we subtract its value from sum and recursively try to make the remaining amount with the same value. If we exclude it, we move to (m+1).
Mathematically the recurrence relation will look like the following:
- count(m, n) = count(m, n-m) + count(m+1, n)
Base cases:
- count(m, n) = 0, if n < 0 or m > n.
- count(m, n) = 1, if n == 0.
3
If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming:
1. Optimal Substructure: Number of ways to make sum n at value m, i.e., count(m, n), depends on the optimal solutions of the subproblems count(m, n-m) and count(m+1, n). By combining these optimal substructures, we can efficiently calculate the number of ways to make target sum n at value m.
2. Overlapping Subproblems: While applying a recursive approach in this problem, we notice that certain subproblems are computed multiple times.
3
The idea is to fill the DP table based on previous values. For each value m, we either include it or exclude it to compute the number of ways needed for each sum n. The table is filled in an iterative manner from i = n to i = m and for each sum from 1 to n.
The dynamic programming relation is as follows:
- if (sum-i) is greater than equal to 0, then dp[i][sum] = dp[i][sum-i] + dp[i+1][sum]
- else dp[i][sum] = dp[i+1][sum].
3
In previous approach of dynamic programming we have derive the relation between states as given below:
- if (sum-i) is greater than 0, then dp[i][sum] = dp[i][sum-i] + dp[i+1][sum]
- else dp[i][sum] = dp[i+1][sum].
If we observe that for calculating current dp[i][sum] state we only need previous row dp[i-1][sum] or current row dp[i][sum-i]. There is no need to store all the previous states just one previous state is used to compute result.
3