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;
Arrays.sort(pipes);
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 Educative.io charges, you would think that the solutions would be of good quality, at least.