方案一:遍历所有子数组,复杂度o(n^3)
public static int Max1() { int[] array = { 1, -2, 3, 10, -4, 7, 2, -5 }; int length = array.Length; int maximum = array[0]; int sum = 0; for (int i = 0; i < length; i++) //一二两层循环用来遍历子数组 { for (int j = i; j < length; j++) { for (int k = i; k <= j; k++) //第三层循环用来计算子数组的和 { sum += array[k]; } if (sum > maximum) maximum = sum; sum = 0; } } return maximum; }
方案二:抛弃掉临时累加和为负数的子序列,复杂度o(n)
public static int Max2() { int[] array = { 1, -2, 3, 10, -4, 7, 2, -5 }; int length = array.Length; int maximum =array[0]; int sum = 0; for (int i = 0; i < length; i++) { if (sum < 0) sum = array[i]; //和为负数,后面无论是正数还是负数都需要被覆盖掉 else sum += array[i]; if (maximum < sum) maximum = sum; } return maximum; }