Given a list of integer each representing the length of each stick and an integer which tells how many times we can break a stick into half parts, we have to find maximum desired length sticks can be obtained from the group of sticks.
Note 1: When we break a stick it gets converted into two half parts for example for a stick of length 10 two sticks can be obtained of both 5 in length and for a stick of length 5 two sticks will be obtained of length 2 and 3 respectively.
Note 2: Discarded part can’t be used again for making sticks such that if a stick of length 11 is given we can break it into 5 and 6 of length pieces then we have to discard one of the pieces which can’t be used further.
list = [2, 3, 4, 11]
n = 2
desired_length = 3
Maximum sticks of desired length that can be obtained are : 3
We already have one stick of length 3 and two more sticks can be obtained
by breaking stick of length 11 into [5, 3, 3] pieces therefore total sticks will be 3.
list = [2, 1, 4, 5]
n = 2
desired_length = 4
Maximum sticks of desired length that can be obtained are : 1
We already have one stick of length 4 and no more sticks can be obtained
by breaking any stick therefore total sticks will be 1
To solve the problem mentioned above we will first do a linear search operation to find all the sticks which have exact same length as of the desired stick length and count them. We will then store the count in the variable. Obviously, we have to discard all the sticks which have a length less than the desired length as with them we can’t make any desired length stick. Then pass the value of sticks that have a length more than the desired length to a function that calculates how many sticks can be obtained by breaking them. With the help of recursion find a number of ways in which sticks can be obtained.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live