import java.util.ArrayList;import java.util.List;public class LeastSumDiff { public static void main(String args[]) { int[] a1 = { 100, 99, 98, 1, 2, 3 }; // int[] a1 = { 40, 50 }; int[] a2 = { 1, 2, 3, 4, 5, 40 }; // int[] a2 = { 20, 15 };// int a1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 90, 0, 0, 100 };// int a2[] = { -1, -2, -100, -3, 99, -222, -2, -3, -5, -88, 11, 12, 13 }; //int leastSum = leastSumDiff(a1, a2); int leastSum = leastSumDiff1(a1, a2); for (int i : a1) { System.out.print(i + " "); } System.out.println(); for (int i : a2) { System.out.print(i + " "); } System.out.println(); System.out.println(leastSum); } public static int leastSumDiff(int[] a1, int[] a2) { int leastSum = 0; int sumA = 0; int sumB = 0; for (int i = 0; i < a1.length; i++) { sumA += a1[i]; sumB += a2[i]; } leastSum = Math.abs(sumA - sumB); for (int i = 0; i < a1.length; i++) { for (int j = 0; j < a2.length; j++) { int tmp = sumA + a2[j] - a1[i]; int tmp1 = sumB + a1[i] - a2[j]; int tmpLeast = Math.abs(tmp - tmp1); if (leastSum > tmpLeast) { int tmpa1 = a1[i]; a1[i] = a2[j]; a2[j] = tmpa1; sumA = tmp; sumB = tmp1; leastSum = tmpLeast; if (tmpLeast == 0) { return 0; } } } } return leastSum; } // a[i] - b[j] is around (sumA - sumB)/2; public static int leastSumDiff1(int[] a, int[] b) { int leastSum = 0; int sumA = 0; int sumB = 0; for (int i = 0; i < a.length; i++) { sumA += a[i]; sumB += b[i]; } leastSum = Math.abs(sumA - sumB); int nextToLeastSum = leastSum; int tmpJ = 0; ListaL = new ArrayList (); List bL = new ArrayList (); for (int i = 0; i < a.length; i++) { boolean found = false; for (int j = 0; j < b.length; j++) { int currentGap = Math.abs(a[i] - b[j]) * 2; if (leastSum >= Math.abs(a[i] - b[j]) * 2) { if (!(leastSum > Math.abs(sumA - a[i] + b[j] - (sumB + a[i] - b[j])))) { continue; } if (!found) { nextToLeastSum = currentGap; tmpJ = j; found = true; } else { if (nextToLeastSum < currentGap) { nextToLeastSum = currentGap; tmpJ = j; } } } } if (found) { sumA = sumA - a[i] + b[tmpJ]; sumB = sumB + a[i] - b[tmpJ]; leastSum = Math.abs(sumA - sumB); int tmpa1 = a[i]; a[i] = b[tmpJ]; b[tmpJ] = tmpa1; nextToLeastSum = leastSum; } if (leastSum == 0) { return 0; } } return leastSum; }}