Search⌘ K

Solution: Connecting 'n' Pipes with Minimum Cost

Explore two greedy algorithm solutions to connect 'n' pipes with minimum total cost. Understand how sorting and MinHeap data structures optimize the process and analyze time complexities for each method.

Solution #1: Sorting

Java
class MinimumCost {
public static int minCost(int[] pipes) {
int cost = 0;
int n = pipes.length;
for (int i = 0; i < n - 1; i++) {
Arrays.sort(pipes); //Sorting the array
int prev_cost = cost; // store previous cost for later use
cost = (pipes[i] + pipes[i + 1]); //find current cost
pipes[i + 1] = cost; //insert in array
cost = cost + prev_cost; //add with previous cost
}
return cost;
}
}
class Main{
public static void main(String[] args) {
int[] pipes = {4, 3, 2, 6 };
System.out.println("Total cost for connecting pipes is " + MinimumCost.minCost(pipes));
int[] pipes1 = {1, 1, 2, 6};
System.out.println("Total cost for connecting pipes1 is " + MinimumCost.minCost(pipes1));
}
}

Explanation

  • Start by sorting the pipes array, shown in line 9.

  • Next, find the cost of connecting two adjacent pipes by summing the cost at the current index and the next index of the pipes array (line 10).

  • Insert this cost into the array (line 11).

  • Next, update the cost by adding it to the previously calculated cost; this is to find the total cost (line 12).

  • Return the total cost at the end (line 14).

Time complexity

The time complexity for this solution is ...