求子数组的最大和

- 日理万妓 2022-08-02 01:18 249阅读 0赞

题目:
输入一个整形数组,数组里有正数也有负数。
数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。
求所有子数组的和的最大值。要求时间复杂度为O(n)。

例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,

因此输出为该子数组的和18。

  1. // maxofsubarray.cpp : 定义控制台应用程序的入口点。
  2. //
  3. #include "stdafx.h"
  4. #include<vector>
  5. #include<iostream>
  6. using namespace std;
  7. int maxofsubarray(int*in, int len, int startpos);
  8. int sumofvec(vector<int>vec);
  9. int maxofvec(vector<int>vec);
  10. int endpos = 0;
  11. int _tmain(int argc, _TCHAR* argv[])
  12. {
  13. const int len = 8;
  14. int a[len] = { 1, -2, 3, 10, -4, 7, 2, -5 };
  15. int ss = 0;
  16. int max = 0;
  17. while (ss < len)
  18. {
  19. //endpos=0;
  20. int mm=maxofsubarray(a, len, ss);
  21. if (mm > max)
  22. max = mm;
  23. if (endpos == 0)
  24. ss = ss + 1;
  25. else
  26. ss = endpos + 1;
  27. cout << endpos << endl;
  28. }
  29. cout << max << endl;
  30. system("pause");
  31. return 0;
  32. }
  33. int maxofsubarray(int*in, int len,int startpos)
  34. {
  35. vector<int>aa,bb;
  36. while (in[startpos] <= 0)
  37. {
  38. ++startpos;
  39. if (startpos >= len)
  40. return -1;
  41. }
  42. bb.push_back(in[startpos]);
  43. int max = in[startpos];
  44. for (int i = startpos+1; i < len; i++)
  45. {
  46. if (i == len - 1)
  47. endpos = 0;
  48. if (in[i]>=0)
  49. bb.push_back(in[i]);
  50. if (in[i] < 0)
  51. {
  52. int v = sumofvec(bb);
  53. aa.push_back(v);
  54. if (in[i] + v >= 0)
  55. {
  56. bb.push_back(in[i]);
  57. continue;
  58. }
  59. else
  60. {
  61. endpos = i;
  62. break;
  63. }
  64. }
  65. }
  66. return maxofvec(aa);
  67. }
  68. int sumofvec(vector<int>vec)
  69. {
  70. vector<int>::iterator it;
  71. int sum = 0;
  72. for (it = vec.begin(); it != vec.end(); it++)
  73. sum += *it;
  74. return sum;
  75. }
  76. int maxofvec(vector<int>vec)
  77. {
  78. vector<int>::iterator it;
  79. int max = 0;
  80. for (it = vec.begin(); it != vec.end(); it++)
  81. if(*it>max)
  82. max=*it;
  83. return max;
  84. }

简洁的解法

  1. int main()
  2. {
  3. int a[10]={1,-8,6,3,-1,5,7,-2,0,1};
  4. cout<<maxSum(a,10)<<endl;
  5. return 0;
  6. }
  7. int maxSum(int* a, int n)
  8. {
  9. int sum=0;
  10. int b=0;
  11. for(int i=0; i<n; i++)
  12. {
  13. if(b<=0) //此处修正下,把b<0改为 b<=0
  14. b=a[i];
  15. else
  16. b+=a[i];
  17. if(sum<b)
  18. sum=b;
  19. }
  20. return sum;
  21. }
  22. 运行结果,如下:
  23. 20
  24. Press any key to continue
  25. ------------------------------------------------------------

发表评论

表情:
评论列表 (有 0 条评论,249人围观)

还没有评论,来说两句吧...

相关阅读

    相关

    / 输入一个整数数组nums,请你在其中找一个和最大的子数组,返回这个子数组的和 dp[i]表示以nums[i]的最大子数组和 状态 / public c

    相关

    题目:  输入一个整形数组,数组里有正数也有负数。  数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。  求所有子数组的和的最大值。要求时间复杂度为