循环一维子数组最大和

1、设计思路:

将一维数组首尾相接赋值到一个新的一位数组中,依次来代替循环数组,再按照一维数组求和最大子数组求得子数组即可;

2、源代码:

#include<iostream>

#include<ctime>

#define N 10

#define M 2*N

using namespace std;

 

void main()

{

         int a[N];              //整数数组

         int b[M];              //代替循环数组

         int e, f;                //数值范围

         int i, j, k, l;        //控制循环变量

         int sum, max;          //和与最大值

         int m, n;              //记录子数组

         int p, q;              //输出子数组的位置

 

         cout << "请输入数值范围:";

         cin >> e >> f;

 

         srand((unsigned)time(NULL));

         for (i = 0; i<N; i++)                     //生成一维数组

         {

                   a[i] = rand()%(f - e + 1) + e;

                   cout << a[i] << "   ";

         }

         cout << endl;

 

         for (i = 0; i < N; i++)                  //将一维数组复制到一个2倍长的新一维数组中

         {

                   b[i] = a[i];

         }

         for (i = N; i < M; i++)

         {

                   b[i] = a[i - N];

         }

         max = b[0];             //初始化最大值

 

         for (l = 0; l < N; l++)                //求得最大值和子数组下标

         {

                   for (i = l; i < N + l; i++)

                   {

                            for (j = l; j <= l + i; j++)

                            {

                                     sum = 0;

                                     for (k = j; k <= i; k++)

                                               sum = sum + b[k];

                                     if (sum>=max)

                                     {

                                               max = sum;

                                               m = j;

                                               n = i;

                                     }

                            }

                   }

         }

 

         if (m >= N)                               //计算子数组的位置

         {

                   p = m - N + 1;

         }

         else

         {

                   p = m + 1;

         }

         if (n >= N)

         {

                   q = n - N + 1;

         }

         else

         {

                   q = n + 1;

         }

 

         //////////////////输出子数组的信息以及最大值

         cout << "子数组的最大值为:" << max << endl;

         cout << "子数组是第" << p << "个数,到第" << q << "个数。" << endl;

         cout << "子数组是:";

         for (i = m; i <= n; i++)

         {

                   cout << b[i] << "  ";

         }

         cout << endl;

 

}

3、截图:

4、总结

结对开发时,领航者还是很重要的,讨论时的思路清晰程度决定了编写代码的速度,也决定了代码的优劣;

两个人做一个开发时,对方可以从不同的角度来弥补自己思路上的漏洞,使程序更完美。

posted on 2015-04-11 16:11  温柔的心  阅读(256)  评论(1编辑  收藏  举报

导航