Cutting Rod Problem to get maximum profit
💻 coding

Cutting Rod Problem to get maximum profit

1 min read 173 words
1 min read
ShareWhatsAppPost on X
  • 1The Cutting Rod Problem involves determining how to cut a rod to maximize profit based on given prices for different lengths.
  • 2Dynamic programming is utilized to solve the problem efficiently, using a two-dimensional array to store maximum profits.
  • 3The time complexity of the provided solution is O(n*m), where n is the number of lengths and m is the rod's total length.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The Cutting Rod Problem involves determining how to cut a rod to maximize profit based on given prices for different lengths."

Cutting Rod Problem to get maximum profit

You are given a rod of a particular length and prices at which those different lengths of this rod can be sell, how will you cut this rod to maximize your profit?

We will be using dynamic programming to solve this problem. Java Solution for the problem is given below:

import java.util.HashMap;

public class CuttingRodProblem {
	
	private static int max(int a, int b) {
		return a>b?a:b;
	}
	
	public static void main(String[] args) {
		//adding extra 0 in beginning as dummy value.
		Integer[] rodLenArr = new Integer[] {0, 1, 2, 3, 4};
		Integer length = 5;
		HashMap<Integer,Integer> profit = new HashMap<Integer,Integer>();
		profit.put(rodLenArr[0], 0);
		profit.put(rodLenArr[1], 2);
		profit.put(rodLenArr[2], 5);
		profit.put(rodLenArr[3], 7);
		profit.put(rodLenArr[4], 8);
		
		Integer[][] dp = new Integer[rodLenArr.length+1][length+1];
		for(int i=0;i<rodLenArr.length;i++) {
			for(int j=0;j<length+1;j++) {
				if(j==0 || i == 0)
					dp[i][j]=0;
				else if(j<rodLenArr[i]) {
					dp[i][j]=dp[i-1][j];
				}
				else {
					dp[i][j]=max(dp[i-1][j],
							dp[i][j-rodLenArr[i]]
									+profit.get(rodLenArr[i]));
				}
			}
		}
		
		System.out.println(dp[rodLenArr.length-1][length]);
	}
}

Time Complexity of the above solution will be n*m. Where n is the total number of different lengths of the rod while m is the length of the given rod.

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 13 July 2018 · 1 min read · 173 words

Part of AskGif Blog · coding

You might also like

Cutting Rod Problem to get maximum profit | AskGif Blog