DEV Community

Prashant Mishra
Prashant Mishra

Posted on • Originally published at codingninjas.com

2

Rod cutting Problem (similar to unbounded knapsack)

Problem:
Given a rod of length n units, the rod can be cut into different sizes and each size has a cost associated with it. Determine the maximum cost that can be achieved by cutting the rod and selling it in the market.

import java.util.*;
public class Solution {
    public static int cutRod(int price[], int n) {
        //intuition 
        /*
        Since, we have to maximize the profit by cutting the rod in different length
        let say length of the rod is 5
        and the prices for cutting in different lengths are : 2 5 7 8 10
        so we will have to keep on picking lengths(we could take a length any 
        no of times to maximize the profit of selling the rod) until there is no more length is left to be picked from;
        This is exactly similar to unbounded knapsack problem:
        */
        int dp[][] = new int[n][n+1];
        for(int row []: dp) Arrays.fill(row,-1);
        return maxProfit(n-1,price,n,dp);
    }
    public static int maxProfit(int index, int[] price,int target,int dp[][]){
        if(index==0){
            return (target/(index+1))*price[index];
        }
        if(dp[index][target]!=-1) return dp[index][target];
        int take = 0;
        if(target>=index+1){
            take  = price[index]+maxProfit(index,price,target-(index+1),dp);
        }
        int dontTake = 0 + maxProfit(index-1,price,target,dp);
        return dp[index][target] = Integer.max(take,dontTake);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.