As discussed above, the time complexity is cubical because of comparing the previous row values for calculating the max profit. So, we will try to reduce the innermost loop. Look at the diagram given below:
The above diagram shows that for calculating the value of v23 we are applying the innermost loop which compares the three quantities written at the right in the diagram. So, if we look carefully, we can notice that p3 is common in all of these. So, the above terms can just be rearranged as follows:
Since p3 is common, we realize that we just have to find the max between all these terms without considering p3. If we again look at the equations carefully, we realize that we are subtracting from the value vij its own column values.
Soo, now it doesn't seem like a big task, does it? We can easily remove the third loop by finding the max among all these values while traversing only. How? Look at the code given below: