题目:
数组中整数有正有负
求一连续子段,使得和最大化
例如:
2,4,-7,5,2,-1,2,-4,3
最大连续段:
5,2,-1,2
其最大和为8
分治法(O(NlogN)):
public class MaximumSequenceSum {
static int work(int[] a, int begin, int end) {
if(end-begin==1) {
if(a[begin]>0) return a[begin];
return 0;
}
int k = (begin+end)/2;
int t1 = work(a, begin, k);
int t2 = work(a, k, end);
int sum = 0;
int ta = 0;
int tb = 0;
for(int i=k-1; i>=begin; i--) {
sum += a[i];
if(sum > ta) ta=sum;
}
sum = 0;
for(int i=k; i<end; i++) {
sum += a[i];
if(sum > tb) tb=sum;
}
int t = ta + tb;
int max = 0;
if(t1 > max) max = t1;
if(t2 > max) max = t2;
if(t > max) max = t;
return max;
}
public static void main(String[] args) {
int[] a = {2,4,-7,5,2,-1,2,-4,3};
System.out.println(work(a, 0, a.length));
}
}
动态规划(O(N)):
public class MaximumSequenceSum {
static int end,start;//结束、开始下标
static int max;
public static int maxSum(int[] arr) {
int temp = 0, k = 0;
for(int i = 0; i < arr.length; i++) {
temp += arr[i];
if(temp < 0) {
k = i + 1;
temp = 0;
} else {
if(temp > max) {
end = i;
start = k;
max = temp;
}
}
}
return max;
}
public static void main(String[] args) {
int[] arr = {1,-2,3,10,-4,7,-4,5,-5};
System.out.println("maxSum:"+maxSum(arr)+",start:"+start+",end:"+end);
}
}