Chinaunix首页 | 论坛 | 博客
  • 博客访问: 199602
  • 博文数量: 51
  • 博客积分: 1435
  • 博客等级: 上尉
  • 技术积分: 590
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-05 18:33
文章分类

全部博文(51)

文章存档

2012年(17)

2011年(34)

分类: C/C++

2012-04-19 10:10:49

原有题目没有考虑到全是负数,输出最大负数,而是采取输出0; (function(w, d, g, J) { var e = J.stringify || J.encode; d[g] = d[g] || {}; d[g]['showValidImages'] = d[g]['showValidImages'] || function() { w.postMessage(e({'msg': {'g': g, 'm':'s'}}), location.href); } })(window, document, '__huaban', JSON);
好的参考资料 http://blog.csdn.net/v_july_v/article/details/6444021 

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. /*遍历求子数组最大和 时间复杂度为o(n^2)*/
  4. int maxsum(int *a,int n)
  5. {
  6.     int s1 = 0,s2 = 0;
  7.     int i,j;

  8.     for(i = 0;i < n; i++)
  9.     {
  10.         s1 = 0;
  11.         for(j = i;j < n; j++)
  12.         {
  13.             s1 += a[j];
  14.             if(s1 > s2)
  15.                 s2 = s1;
  16.         }
  17.     }
  18.     return s2;
  19. }
  20. /* 求子数组最大和 时间复杂度为o(n)*/
  21. int maxsum2(int *a,int n)
  22. {
  23.     int i;
  24.     int s1 = 0,s2 = 0;

  25.     for(i = 0;i < n;i++)
  26.     {
  27.         s1 += a[i];
  28.         if(s1 < s2)
  29.             s1 = (s1 > a[i]) ? s1 : a[i];
  30.         else if(s1 >= s2)
  31.             s2 = s1 = (s1 > a[i]) ? s1 : a[i];
  32.     }
  33.     return s2;
  34. }
  35. int maxsum3(int *a,int n)
  36. {
  37.     int i;
  38.     int sum = 0,b = 0;

  39.     for(i = 0;i < n;i++)
  40.     {
  41.         if(b < 0)
  42.           b = a[i];
  43.         else
  44.           b += a[i];
  45.         if(b > sum)
  46.             sum = b;
  47.     }
  48.     return sum;
  49. }
  50. /*全为负数时输出最大负数*/
  51. int maxsum4(int *a,int n)
  52. {
  53.     int i;
  54.     int sum = a[0] ;
  55.     int b = 0;

  56.     for(i = 0;i < n;i++)
  57.     {
  58.         if(b < 0)
  59.           b = a[i];
  60.         else
  61.           b += a[i];
  62.         if(b > sum)
  63.             sum = b;
  64.     }
  65.     return sum;
  66. }
  67. int main()
  68. {
  69.     int array[] = {-1,2,4,3,-6,8,-1,10,-3,8};

  70.     int n = sizeof(array)/sizeof(array[0]);
  71.     int sum1 = 0,sum2 = 0,sum3 = 0;
  72.     sum1 = maxsum(array,n);
  73.     printf("max sum1 of array :%d\n",sum1);

  74.     sum2 = maxsum2(array,n);
  75.     printf("max sum2 of array :%d\n",sum2);

  76.     sum3 = maxsum3(array,n);
  77.     printf("max sum3 of array :%d\n",sum3);
  78.     int array1[] = {-1,-2,-3,-4};
  79.     int n1 = sizeof(array1)/sizeof(array1[0]);
  80.     int sum4;
  81.     sum4 = maxsum4(array1,n1);
  82.     printf("max sum4 of array :%d\n",sum4);

  83.     printf("Hello world!\n");
  84.     return 0;
  85. }

阅读(2075) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~