Skip to content

Commit 21a0060

Browse files
greedy solution for minimum chocolate cutting cost
1 parent d23a0ec commit 21a0060

File tree

1 file changed

+62
-0
lines changed
  • src/main/java/com/thealgorithms/greedyalgorithms

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package com.thealgorithms.greedyalgorithms;
2+
3+
import java.util.Arrays;
4+
import java.util.Collections;
5+
6+
/**
7+
* Greedy approach to minimize the cost of cutting a chocolate bar into 1x1 pieces.
8+
*/
9+
public class Chocola {
10+
11+
/**
12+
* Calculates the minimum cost of cutting the chocolate bar.
13+
*
14+
* @param costVer Cost of vertical cuts (size m-1)
15+
* @param costHor Cost of horizontal cuts (size n-1)
16+
* @return Minimum total cost
17+
*/
18+
public static int minCostOfCuttingChocolate(Integer[] costVer, Integer[] costHor) {
19+
Arrays.sort(costVer, Collections.reverseOrder());
20+
Arrays.sort(costHor, Collections.reverseOrder());
21+
22+
int h = 0, v = 0;
23+
int hp = 1, vp = 1;
24+
25+
int cost = 0;
26+
27+
while (h < costHor.length && v < costVer.length) {
28+
if (costHor[h] >= costVer[v]) {
29+
cost += costHor[h] * vp;
30+
h++;
31+
hp++;
32+
} else {
33+
cost += costVer[v] * hp;
34+
v++;
35+
vp++;
36+
}
37+
}
38+
39+
while (h < costHor.length) {
40+
cost += costHor[h] * vp;
41+
h++;
42+
hp++;
43+
}
44+
45+
while (v < costVer.length) {
46+
cost += costVer[v] * hp;
47+
v++;
48+
vp++;
49+
}
50+
51+
return cost;
52+
}
53+
54+
public static void main(String[] args) {
55+
int n = 4, m = 5;
56+
Integer[] costVer = {2, 1, 3, 1}; // m-1 cuts
57+
Integer[] costHor = {4, 1, 2}; // n-1 cuts
58+
59+
int totalCost = minCostOfCuttingChocolate(costVer, costHor);
60+
System.out.println("Cost = " + totalCost);
61+
}
62+
}

0 commit comments

Comments
 (0)