题目:返回一个整数数组中最大子数组的和。

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

思路:把每个和放在二维数组中,找出最大数根据i和j的关系就找到最大数组,不过时间复杂度是o(n^2),还在试着用链表的方式可以使他的时间复杂度是o(n^2)输出

代码:

#include <iostream>
#define N 8
using namespace std;

void main()
{
    int fuhao,a[N],b[N][N]={0},k=0;
    int i,j,I,J;
    for (i=0;i<N;i++)
    {
        fuhao=rand()%2;
        a[i]= (fuhao==0) ? -rand()%100:rand()%100;
        cout<<"a["<<i<<"]="<<a[i]<<endl;
    }
    for (j=0;j<N;j++)
    {
        b[0][j]=a[j];
    }
    for(j=0;j<N;j++)
    {
        for (i=1;i<N-j;i++)
        {
                b[i][j]=a[i+j]+b[i-1][j];
        }
    }

    for (i=0;i<N;i++)
    {
        for (j=0;j<N;j++)
        {
            if(b[i][j]>k)
            {
                k=b[i][j];
                I=i;
                J=j;
            }
        }
    }
    cout<<endl;
    cout<<"k="<<k<<endl;
    cout<<"最大子数组为:"<<endl;
    for (i=0;i<I+1;i++,J++)
    {
        cout<<J<<"   "<<a[J]<<endl;
    }
    cout<<endl;
}

 

截图:

一维数组最大子数组(一)

一维数组最大子数组(一)

一维数组最大子数组(一)

相关文章:

  • 2022-03-05
  • 2021-12-09
  • 2021-07-30
  • 2022-03-07
  • 2021-11-20
  • 2021-07-29
  • 2022-01-03
  • 2021-09-18
猜你喜欢
  • 2021-09-19
  • 2022-01-25
  • 2022-02-10
  • 2022-01-16
  • 2021-11-04
  • 2021-11-01
  • 2022-01-21
相关资源
相似解决方案