Last active
July 29, 2019 19:46
-
-
Save RitamChakraborty/2845aa07fbcda2a6e219e8e6341112f1 to your computer and use it in GitHub Desktop.
Optimal Merge Pattern algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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