-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathOptimalFileMerge.java
More file actions
54 lines (38 loc) · 1.38 KB
/
OptimalFileMerge.java
File metadata and controls
54 lines (38 loc) · 1.38 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
48
49
50
51
52
53
package stack_and_queue;
// Java program to implement Optimal File Merge Pattern
import java.util.*;
public class OptimalFileMerge {
// Function to find minimum computation
static int minComputation(int size, int[] files) {
// create a min heap
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int i = 0; i < size; i++) {
// add sizes to priorityQueue
pq.add(files[i]);
}
// variable to count total computations
int count = 0;
while (pq.size() > 1) {
// pop two smallest size element from the min heap
int temp = pq.poll() + pq.poll();
// add the current computations with the previous one's
count += temp;
// add new combined file size to priority queue or min heap
pq.add(temp);
System.out.println(temp);
}
return count;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// no of files
int size = sc.nextInt();
int[] files = new int[size];
for(int i = 0; i < size; i++){
files[i] = sc.nextInt();
System.out.print(files[i] + " ");
}
// total no of computations do be done final answer
System.out.println("Minimum Computations = " + minComputation(size, files));
}
}