From 21a0060e6605a9dfb232a0dcf02cd7cf8c551df3 Mon Sep 17 00:00:00 2001 From: Aanya Srivastava Date: Sun, 25 May 2025 16:11:42 +0530 Subject: [PATCH 1/2] greedy solution for minimum chocolate cutting cost --- .../greedyalgorithms/Chocola.java | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/main/java/com/thealgorithms/greedyalgorithms/Chocola.java diff --git a/src/main/java/com/thealgorithms/greedyalgorithms/Chocola.java b/src/main/java/com/thealgorithms/greedyalgorithms/Chocola.java new file mode 100644 index 000000000000..8389e152f414 --- /dev/null +++ b/src/main/java/com/thealgorithms/greedyalgorithms/Chocola.java @@ -0,0 +1,62 @@ +package com.thealgorithms.greedyalgorithms; + +import java.util.Arrays; +import java.util.Collections; + +/** + * Greedy approach to minimize the cost of cutting a chocolate bar into 1x1 pieces. + */ +public class Chocola { + + /** + * Calculates the minimum cost of cutting the chocolate bar. + * + * @param costVer Cost of vertical cuts (size m-1) + * @param costHor Cost of horizontal cuts (size n-1) + * @return Minimum total cost + */ + public static int minCostOfCuttingChocolate(Integer[] costVer, Integer[] costHor) { + Arrays.sort(costVer, Collections.reverseOrder()); + Arrays.sort(costHor, Collections.reverseOrder()); + + int h = 0, v = 0; + int hp = 1, vp = 1; + + int cost = 0; + + while (h < costHor.length && v < costVer.length) { + if (costHor[h] >= costVer[v]) { + cost += costHor[h] * vp; + h++; + hp++; + } else { + cost += costVer[v] * hp; + v++; + vp++; + } + } + + while (h < costHor.length) { + cost += costHor[h] * vp; + h++; + hp++; + } + + while (v < costVer.length) { + cost += costVer[v] * hp; + v++; + vp++; + } + + return cost; + } + + public static void main(String[] args) { + int n = 4, m = 5; + Integer[] costVer = {2, 1, 3, 1}; // m-1 cuts + Integer[] costHor = {4, 1, 2}; // n-1 cuts + + int totalCost = minCostOfCuttingChocolate(costVer, costHor); + System.out.println("Cost = " + totalCost); + } +} From 50f97e29dfb997ba2ed7f7e631b80acf4088dfc0 Mon Sep 17 00:00:00 2001 From: Aanya Srivastava Date: Sun, 25 May 2025 16:18:09 +0530 Subject: [PATCH 2/2] greedy solution for minimum chocolate cutting cost --- src/main/java/com/thealgorithms/greedyalgorithms/Chocola.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/thealgorithms/greedyalgorithms/Chocola.java b/src/main/java/com/thealgorithms/greedyalgorithms/Chocola.java index 8389e152f414..f3244e4afad9 100644 --- a/src/main/java/com/thealgorithms/greedyalgorithms/Chocola.java +++ b/src/main/java/com/thealgorithms/greedyalgorithms/Chocola.java @@ -6,6 +6,7 @@ /** * Greedy approach to minimize the cost of cutting a chocolate bar into 1x1 pieces. */ + public class Chocola { /** @@ -60,3 +61,4 @@ public static void main(String[] args) { System.out.println("Cost = " + totalCost); } } +