rajeshinternshala

Untitled

Feb 25th, 2024
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.22 KB | None | 0 0
  1. public static long calculateMaximumProfit(int cost_per_cut, int metal_price, int[] lengths) {
  2.  
  3.     long maxProfit = 0;
  4.     long curProfit = 0;
  5.     int maxLength = 0;
  6.     int totalRods = 0;
  7.     int totalCuts = 0;
  8.     Arrays.sort(lengths);
  9.     // Find out maximum length
  10.     for (int curLength : lengths) {
  11.         maxLength = Math.max(maxLength, curLength);
  12.     }
  13.  
  14.     // For each of the possible rod lengths, calculate possible profit
  15.     for (int curLength = 1; curLength <=maxLength; curLength++) {        
  16.         int prevSum=0;
  17.         // Cut each of the rods into smaller rods of size curLength
  18.         // Count total rods and total cuts
  19.         for (int length : lengths) {
  20.             int cut = 0;
  21.             int waste = 0;
  22.             if(length%curLength==0){
  23.                 cut=(length/curLength)-1;
  24.             }else{
  25.                 cut=length/curLength;
  26.             }
  27.             waste=length%curLength;
  28.             int profit=Math.max(prevSum,prevSum+(length*metal_price-cut*cost_per_cut-waste*metal_price));
  29.             prevSum=profit;
  30.         }
  31.  
  32.         curProfit=prevSum;
  33.         // Calculate maximum profit
  34.         maxProfit = Math.max(maxProfit, curProfit);
  35.     }
  36.  
  37.     return maxProfit;
  38. }
Add Comment
Please, Sign In to add comment