-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueHomework.java
More file actions
42 lines (36 loc) · 1.05 KB
/
Copy pathQueueHomework.java
File metadata and controls
42 lines (36 loc) · 1.05 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
import java.util.*;
public class QueueHomework {
// Generate Binary number
public static void printBinary(int n){
Queue<String> q = new LinkedList<>();
q.add("1");
while(n-- > 0){
String s1 = q.peek();
q.remove();
System.out.print(s1 + " ");
String s2 = s1;
q.add(s1 + "0");
q.add(s2 + "1");
}
}
public static int minCost(int size , int arr[]){
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int i = 0; i < arr.length; i++){
pq.add(arr[i]);
}
int res = 0;
while(pq.size() > 1){
int first = pq.poll();
int second = pq.poll();
res += first + second;
pq.add(first + second);
}
return res;
}
public static void main(String[] args) {
// printBinary(100);
int arr[] = {1,2,3};
int size = arr.length;
System.out.print(minCost(size, arr));
}
}