Skip to content

Instantly share code, notes, and snippets.

@RitamChakraborty
Last active July 29, 2019 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RitamChakraborty/2845aa07fbcda2a6e219e8e6341112f1 to your computer and use it in GitHub Desktop.
Save RitamChakraborty/2845aa07fbcda2a6e219e8e6341112f1 to your computer and use it in GitHub Desktop.
Optimal Merge Pattern algorithm
import java.util.*;
public class OptimalMergePattern {
public static void main(String[] args) {
System.out.println(getLeastMergingCost(new int[]{20, 30, 10, 5, 30}));
}
private static int getLeastMergingCost(int[] list) {
Arrays.sort(list);
int maxCost = list[0];
int minMergingCost = maxCost;
int n = list.length;
int i = 0;
while (i < n) {
if (i == 0) {
if ((i + 1) < n) {
maxCost += list[i + 1];
i += 2;
} else {
break;
}
} else {
if ((i + 1) < n) {
if ((maxCost + list[i]) > (list[i] + list[i + 1])) {
minMergingCost += list[i] + list[i + 1];
maxCost += list[i] + list[i + 1];
i += 2;
} else {
maxCost += list[i];
i++;
}
} else {
maxCost += list[i];
i++;
}
}
minMergingCost += maxCost;
}
return minMergingCost;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment