Given a rod of length N meters, and the rod can be cut in only 3 sizes A, B and C. The task is to maximizes the number of cuts in rod. If it is impossible to make cut then print -1.
Input: N = 17, A = 10, B = 11, C = 3
The maximum cut can be obtain after making 2 cut of length 3 and one cut of length 11.
Input: N = 10, A = 9, B = 7, C = 11
It is impossible to make any cut so output will be -1.
- Let us assume x, y, and z numbers of rods of sizes A, B, and C respectively are cut. And this can be written as a linear equation: x*A + y*B + z*C = N
- Now, simply iterate over all possible value of x and y and compute z using (N – x*A + y*B) / c.
- If x*A + y*B + z*C = N, then it is one of the possible answers.
- Finally compute the maximum value of x + y + z.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The problem can be solve using Dynamic Programming.
- Create a dp array of size N and initialise all value to INT_MIN.
- Set dp = 0, as it will be base case for our approach.
- Iterate from 1 to N and check if it is possible to make a cut of any of possible length i.e A, B and C, and update dp[i] to minimum of all.