/** * 获取左边最大的字段和(连续的) * @param a * @return */ publicstaticintgetLeft(int[] a){ int left = 0, sum = 0, left_max = 0; int center = (a.length - 1) / 2; // 遍历左边 // 获取左边的最大子段和 for (int i = center; i >= left; i--) { sum += a[i]; if (sum > left_max) left_max = sum; } return left_max; }
/** * 获取右边的子段和(连续) * @param a * @return */ publicstaticintgetRight(int[] a){ int right = a.length - 1, sum = 0, right_max = 0; int center = (a.length - 1) / 2; for (int i = center + 1; i <= right; i++) { sum += a[i]; if (sum > right_max) right_max = sum; } return right_max; }
publicstaticvoidmain(String[] args){ int[] a = { -2, 11, -4, 13, -5, -2 }; int left_max = getLeft(a); int right_max = getRight(a); int sum = left_max + right_max; System.out.println("第一种情况:left_max:" + left_max); System.out.println("第二种情况:right_max:" + right_max); System.out.println("第三种情况:sum:" + sum);
/** * 设置最大B:最大字段和 * * a,b,beg数组长度相同 * * @param n * 长度,数组位置下标 * @param b * @param a * @param beg */ publicstaticvoidsetB(int n, int[] b, int[] a, int[] beg){ // 下标是0 if (n == 0) { b[n] = a[n]; beg[n] = n; } else { // n递减 setB(n - 1, b, a, beg); // 最大值b[n] b[n] = max(b[n - 1] + a[n], a[n]); if (b[n - 1] + a[n] > a[n]) beg[n] = beg[n - 1]; else beg[n] = n; } }
/** * 最大子数组 b[] 最大子段数组 * * @param a */ publicstaticvoidmaxChildArry(int[] a){ // 新建a长度的b数组 int b[] = newint[a.length]; // 新建最大子段和的开始的位置 int beg[] = newint[a.length]; // a,b数组第一位相同 b[0] = a[0]; // 遍历数组 for (int n = 0; n < b.length; n++) setB(n, b, a, beg); // 最大的数字 int maxsum = b[getMaxElementIndex(b)]; System.out.println("MaxSum: " + maxsum); PrtMaxChildArry(a, beg[getMaxElementIndex(b)], getMaxElementIndex(b)); }
/** * 打印最大子段合的子数组 * * @param aa * @param beg * @param end */ publicstaticvoidPrtMaxChildArry(int aa[], int beg, int end){ System.out.print("The Maxmium Child-Array is: { "); for (int i = beg; i <= end; i++) { System.out.print(aa[i] + " "); } System.out.println("}\n");
}
/** * 获取最大值子段合的最大节点下标 * * @param b * @return */ publicstaticintgetMaxElementIndex(int[] b){ int maxele = 0; int i; for (i = 1; i < b.length; i++) { if (b[maxele] < b[i]) { maxele = i; } } return maxele;