Hey coder. We are going to start with a new question, "Rod Cutting" in this article.
We first want you to go through the problem to understand its outline better.
Important Link : Problem Link, Solution Video Link
Hey coder. We are going to start with a new question, "Rod Cutting" in this article.
We first want you to go through the problem to understand its outline better.
Important Link : Problem Link, Solution Video Link
Say the input array is [1, 5, 8, 9, 10, 17, 17, 20] of size 8 and a rod of length 8.
The above figure shows that a piece of rod of length 1 has a price 1, a piece of rod of length 2 has a price 5, a piece of rod of length 3 has a price 8, and so on.
Hence some of the ways of selling the rod are:
There are 2 strategies for making trees for this problem.
1. CUT STRATEGY :
Figure 3 shows that there are 3 ways possible for a length 3.
Out of the 3 cases, the maximum selling price is 8.
From this we find out the maximum possible way 2-2 which is equal to 10.
If you face any difficulties in solving this dp array you can also watch the solution video.
We summarize all the trees till length 6 in figure shown.
Here, the numbers along the edge denote the price from the original array and the numbers at the vertices marked with star denote the optimized dp array price.
Another way of making trees for rod cutting is given in figure shown below.
We now discuss the method of filling the dp array using left-right strategy.
The storage, meaning and direction is the same as it was in the cut strategy.
We have an option of selecting the best price for length 1 added to itself versus the best price of length 2. Hence out of price 2 and 5, we select 2.
Out of all the prices in figure 10, the maximum price is 22. Hence, it is our final answer.
Code
We write the code of this program using the left-right strategy.
We want you to write it yourself first and then refer to the code given below.
java; true";
With this we conclude our discussion. We hope you were able to understand it
clearly.
If you still have any doubts you can just watch its solution video.
We'll see you in the next question. Goodbye.