求解最大连续子序列和问题
方法一
//求解最大连续子序列和问题 #include<stdio.h> long maxSubSum(int a[],int n){ int i,j,k; long maxSum=a[0],thisSum; for(i=0;i<n;i++){ for(j=i;j<n;j++){ thisSum=0; for(k=0;k<j;k++) thisSum += a[k]; if(thisSum > maxSum) maxSum = thisSum; } } } int main(){ int a[] = {-2,11,-4,13,-5,-2},n=6; printf("a序列的最大连续子序列的和:%d",maxSubSum(a,n)); }
方法二
#include<stdio.h> int maxSubSum(int a[],int n){ int i,j; long maxSum=a[0],thisSum; for(i=0;i<n;i++){ thisSum=0; for(j=i;j<n;j++){ thisSum += a[j]; if(thisSum > maxSum) maxSum = thisSum; } } } int main(){ int a[] = {-2,11,-4,13,-5,-2},n=6; printf("a序列的最大连续子序列的和:%d",maxSubSum(a,n)); }
方法三
#include<stdio.h> int maxSubSum(int a[],int n){ int i,maxSum=0,thisSum=0; for(i=0;i<n;i++){ thisSum += a[i]; if(thisSum < 0) thisSum = 0; if(maxSum < thisSum) maxSum = thisSum; } } int main(){ int a[] = {-2,11,-4,13,-5,-2},n=6; printf("a序列的最大连续子序列的和:%d",maxSubSum(a,n)); }
分治法
动态规划
1 //动态规划 2 #include<stdio.h> 3 #define MaxN 20 4 void maxSubSum(int a[],int b[],int n){ //求b数组 5 int j; 6 b[0] = 0; 7 for(j=1;j<=n;j++){ 8 if(b[j-1] + a[j] > a[j]) 9 b[j] = b[j-1] + a[j]; 10 else 11 b[j] = a[j]; 12 } 13 } 14 void disp(int a[],int b[],int n){ 15 int maxj,i,j,k; 16 maxj = 1; 17 for(j=2;j<=n;j++) 18 if(b[j] > b[maxj]) maxj = j; 19 for(k = maxj;k>=1;k--) 20 if(b[k] <= 0) break; 21 printf("最大连续子序列和:%d\n",b[maxj]); 22 printf("所选子序列:"); 23 for(i = k+1;i<=maxj;i++) 24 printf("%d ",a[i]); 25 printf("\n"); 26 } 27 int main(){ 28 int a[] = {0,-2,11,-4,13,-5,-2},n=6; 29 int b[MaxN]; 30 maxSubSum(a,b,n); 31 disp(a,b,n); 32 return 0; 33 }