-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimumCost.java
More file actions
47 lines (41 loc) · 1.14 KB
/
MinimumCost.java
File metadata and controls
47 lines (41 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package algorithm.greedyalgorithm;
import java.util.Arrays;
/**
* The type Minimum cost.
*/
public class MinimumCost {
/**
* Min cost int.
*
* @param pipes the pipes
* @return the int
*/
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;
}
}
/**
* The type Main.
*/
class Main{
/**
* The entry point of application.
*
* @param args the input arguments
*/
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));
}
}