We are given a rod of length n inches. You can cut it in different parts of integer lengths. Your goal is to get the maximal product of lengths of all parts possible. You must make at least one cut. Assume that the length of rope is more than 2 meters. Reference: https://www.geeksforgeeks.org/maximum-product-cutting-dp-36/
Other references: Algorithm for cutting rod to maximize profit
I want to do this question using bottom up dynamic programming using 2D table.
Assume we have length of 5.
Length of rod
[1] [2] [3] [4] [5]
[0] 0 0 0 0 0
Number of [1] 0 1 2 4 6
cuts [2] 0 1 2
[3] 0
Each cell denotes the maximum product we can get with a given length of rod with a specified number of cuts and also the maximal length remained after cut.
E.g. let's say we need to fill the cell with number of cuts 2 and length of rod eqaul to 4. I will assume that each cell in addition to storing the maximum product of a given length will also store the largest length remained after cut.
After one cut of a length of 4 we get a maximum product of 4 because we cut left part to be 2 and right part to be 2. We store two numbers: 4 for the maximum product and 2 for the largest part. When we are at cell (2, 4), we either can make a cut or not. If we do not make a cut then we look in the current row. And we loop over each length. In this case we loop over length of 2 and length of 3. If it were to be length of 2 then we have remaining 4-2=2 and we multiply to get 4. Then we do the same with 3 to get remaining length to be 1 and multiply this by 2 to get 2.
The other option is to do a cut then we need to look in the upper row. And again we loop from the beginning of that row. Then we select the maximum.
My issue is that I have to each time loop over all the columns i.e. from left till current cell which will make the time complexity be O(n^3).
Is there a way to do this in O(n^2) instead using 2D table?