zoukankan      html  css  js  c++  java
  • 求最大子数组的程序设计

    一、设计思路:通过输入数组的长度和数组中数的取值范围,产生一个随机数组,并用随机数决定正负号。然后在一次循环中,将数组中的数依次相加,若相加大于0则继续相加,若相加小于0则舍弃之前的数,重新开始相加,并且在循环中记录相加产生的最大的数,即为最大子数组的和。

    二、代码:

    #include<iostream>
    using namespace std;
    
    void main()
    {
        int i,x,y,z;
        int s,sum,head,end,h,e;
        cout<<"请输入数组的长度:";
        cin>>x;
        cout<<"请输入数组的取值范围:";
        cin>>z;
        int *a=new int[x];
    
        for(i=0;i<x;i++)
        {
            a[i]=rand()%z;
            y=rand()%2;
            if(y==0)
            {
                a[i]=-a[i];
            }
        }
          
        for(i=0;i<x;i++)
        {
            cout<<a[i]<<" ";
        }
        cout<<endl;
    
        sum=0;
        s=0;
        e=0;
        h=0;
    
        for(i=0;i<x;i++)
        {
            s+=a[i];
            if(s>0)
            {
                e++;
            }
            else
            {
                s=0;
                h=i+1;
                e++;
            }
            if(s>sum)
            {
                sum=s;
                head=h;
                end=e;
            }
        }
        cout<<"最大子数组的和为:"<<sum<<endl;
        cout<<"最大子数组为:";
        for(i=head;i<end;i++)
        {
            cout<<a[i]<<" ";
        }
        cout<<endl;
    
        delete a;
    
    }

    三、结果截图:

    四、总结 :

      在设计思路方面,主要是由于题目对时间复杂度为o(n)的限定,因此需要在一次循环中,判断并计算最大子数的的和和位置,耗费了大量的时间。

      在具体的程序实现方面,主要的问题是对变量的命名产生了混淆,出现了错误,仔细检查后,已改正

    五、项目计划日志

    六、时间记录日志

    七、缺陷记录日志

  • 相关阅读:
    asp.net using library ClosedXML to export excel
    javascript 属性的特性
    javascript 如何避免属性访问错误
    javascript 继承
    Chapter 4 : Character Strings and Formatted Input/Output
    Chapter 3 :Differentiation
    Chapter 3 : Data and C
    Chapter 3 : Data and C
    Chapter 4 : Strings and Formatted Input/Output
    Chapter 1 :Preliminaries
  • 原文地址:https://www.cnblogs.com/act-gh95/p/4360878.html
Copyright © 2011-2022 走看看