/*
* MaxSumArray.c
*
* Created on: 2015年5月5日
* Author: weike
*/
#include<stdio.h>
int besti,bestj;//返回位置i,位置j
/**
* algorithm 1 暴力法O(n^3)
*/
int MaxSum1(int n,int *a){
int sum = 0;
int i,j,k;
for(i=1;i<=n;i++){
for(j=i;j<=n;j++){
int thissum = 0;
for(k=i;k<=j;k++){
thissum += a[k];
}
if(thissum >= sum){
sum = thissum;
besti = i;
bestj = j;
}
}
}
return sum;
}
/**
* algorithm 2 暴力法优化O(n^2)
*/
int MaxSum2(int n,int *a){
int sum = 0;
int i,j;
for(i=1;i<=n;i++){
int thissum = 0;
for(j = i;j <= n;j++){
thissum += a[j];
if(thissum > sum){
sum = thissum;
besti = i;
bestj = j;
}
}
}
return sum;
}
/**
* algorithm 暴力法优化
*/
int MaxSum3(int n,int *a){
int i,j;
int cumarr[20];
cumarr[0] = 0;
for(i=1;i<=n;i++){
cumarr[i] = cumarr[i-1] + a[i];
}
int maxsofar = 0;
int sum;
for(i=1;i<=n;i++){
for(j=0;j<=n;j++){
sum = cumarr[j] - cumarr[i-1];
if(sum > maxsofar){
maxsofar = sum;
besti = i;
bestj = j;
}
}
}
return maxsofar;
}
/**
* algorithm 4 分治法
*/
int MaxSubSum(int *a,int left,int right){
int sum = 0;
int i;
if(left == right)
sum = a[left] > 0 ? a[left] : 0;
else{
int center = (left + right)/2;
//(1)
int leftsum = MaxSubSum(a,left,center);
//(2)
int rightsum = MaxSubSum(a,center+1,right);
//(3)左半部分
int s1 = 0;
int lefts = 0;
for(i=center;i>=left;i--){
lefts += a[i];
if(lefts > s1)
s1 = lefts;
}
//(3)右半部分
int s2 = 0;
int rights = 0;
for(i=center+1;i<=right;i++){
rights += a[i];
if(rights > s2)
s2 = rights;
}
sum = s1 + s2;
if(sum < leftsum)
sum = leftsum;
if(sum < rightsum)
sum = rightsum;
}
return sum;
}
int MaxSum4(int n,int *a){
return MaxSubSum(a,1,n);
}
/**
* algorithm 5 动态规划
*/
int MaxSum5(int n,int *a){
int sum = 0,b = 0;
int i;
for(i=1;i<=n;i++){
if(b>0)
b += a[i];
else
b = a[i];
if(b > sum)
sum = b;
}
return sum;
}
/**
* method main
*/
int main(int argc, char **argv) {
int tmp[] = {0,-2,11,-4,13,-5,-2};
int a[7];
int i;
for(i=1;i<=6;i++){
a[i] = tmp[i];
}
int result1 = MaxSum1(6,a);
int result2 = MaxSum2(6,a);
int result3 = MaxSum3(6,a);
int result4 = MaxSum4(6,a);
int result5 = MaxSum5(6,a);
printf("result1 = %d,i = %d,j = %d\n",result1,besti,bestj);
printf("result2 = %d,i = %d,j = %d\n",result2,besti,bestj);
printf("result3 = %d,i = %d,j = %d\n",result3,besti,bestj);
printf("result4 = %d\n",result4);
printf("result5 = %d\n",result5);
return 0;
}
参考资料:
《计算机算法设计与分析(第三版)》 王晓东著
July博客 结构之法 算法之道