Sorting solution is unnecessary complicated

Why is the first solution (using Sorting) so complicated? What is the need to modify the given input array to store the running cost of connecting the pipes? There is already a variable cost outside the for loop, why not just use that? Here is your solution -

public static int minCost(int[] pipes) {


  int cost = 0;

  int n = pipes.length;

  Arrays.sort(pipes); //Sorting the array

  for (int i = 0; i < n - 1; i++) {

   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;


Here is mine, uses the same logic, but is far simpler, and does not mutate the input array -

public static int minCost(int[] pipes)  {

      int cost = 0;


      int currLength = pipes[0];

      for(int i = 1; i < pipes.length; i++) {

        currLength += pipes[i];

        cost += currLength;

      return cost;


Based on the high fee that charges, you would think that the solutions would be of good quality, at least.

Hi @Manish_Giri. It does not matter if the array is modified after calculating the minimum cost because we did not intend to use this array later. Your solution is also perfect, but you cannot say that the solution provided is not optimal or bad quality. If it was mentioned that the array should not be modified, our solution would have been incorrect, but it works well in this case. But, in terms of complexity, yes your solution is simpler. Happy Learning :smiley: