/**
* 利用动态规划解题:该方法时间复杂度为:o(n),但是额外使用了两个数组空间,其空间复杂度为:o(n)
* 解题思路:对于一个数组,求最大子数组之和,我们可以分为三部分:
* 我们以最后一个元素array[n-1]为例子:
* 1:array[n-1]自己构成最大的子数组
* 2:包含array[n-1]的最大子数组,即以array[n-1]结尾,我们用End[n-1]表示
* 3:不包含array[n-1]的最大子数组,那么求array[0]...array[n-1]的子数组,可以转化为求
* array[0]...array[n-2]的最大子数组
* <p>
* 由以上可知:All[n-1]=max{array[n-1],End[n-1],All[n-1]}
* All[n-1]表示为:array[0]...array[n-1]的最大子数组之和
*/
public static int max(int a, int b) {
return a > b ? a : b;
}
public static int maxInThreeNum(int S_Left, int S_Right, int S_Cross_Left_Right) {
return (S_Left > S_Right ? (S_Left > S_Cross_Left_Right ? S_Left : S_Cross_Left_Right) : (S_Right > S_Cross_Left_Right ?
S_Right : S_Cross_Left_Right));
}
private static void getSumOfSubArray03(int array[]) {
int n = array.length;
int End[] = new int[n];
int All[] = new int[n];
int Rec[] = new int[n];
//初始化:当数组中只有一个元素时
End[0] = All[0] = array[0];
End[n - 1] = All[n - 1] = array[n - 1];
for (int i = 1; i < n; i++) {
//Ent[i]是数组array[i]前i个数最大子数组之和
End[i] = max(End[i - 1] + array[i], array[i]);
if (End[i - 1] > 0) {
Rec[i] = Rec[i - 1];
} else if (End[i - 1] <= 0) {
Rec[i] = i;
}
//All[i]
All[i] = max(End[i], All[i - 1]);
}
System.out.println("方法三:最大子数组之和为:" + All[n - 1]);
System.out.println("End[]数组为:" + Arrays.toString(End));
System.out.println("All[]数组为:" + Arrays.toString(All));
System.out.println("Rec[]数组为:" + Arrays.toString(Rec));
getRec(Rec, End);
}
private static void getRec(int Rec[], int End[]) {
int S = End[End.length - 1];
int l = 0, r = 0;
for (int i = End.length - 1; i > 0; i--) {
if (S < End[i]) {
S = End[i];
r = i;
l = Rec[i];
}
}
System.out.println("左右下标为:" + l + "-" + r);
}