新手 - C++的一道题目运行不过
黄舟
黄舟 2017-04-17 13:41:58
0
2
377

程序新手,正在做计蒜课“挑战难题”中的一道题:最大子阵列:
无奈代码在本地输入多组数据得到结果正常,但是就是通过不了...
希望各位大大能抽空看看我哪里错了,小白十分感谢 >_<

题目:

在一个数组中找出和最大的连续几个数。(至少包含一个数)

例如:

数组 A[] = [−2, 1, −3, 4, −1, 2, 1, −5, 4],则连续的子序列 [4,−1,2,1] 有最大的和 6.

输入格式
第一行输入一个不超过 1000 的整数 n。
第二行输入 n 个整数 A[i]。

输出格式
第一行输出一个整数,表示最大的和。

样例 1
输入:
3
1 1 -2
输出:
2

我的代码:

#include <cstdio>
#include <iostream>

using namespace std;

int AMax(int a[], int N)
{
    int m = 0;
    int sum[N+1][N+1];
    
    for (int p = 0; p <= N; ++p)  //初始化单个元素
    {
        sum[p][p] = a[p];
    }    
    
    for (int i = 0; i < N; ++i)  //求和
    {
        for (int j = i; j < N; ++j)
        {
            sum[i][j+1] = sum[i][j] + a[j+1];
        }
    }
    
    for (int i = 0; i <= N; ++i)  //比较
    {
        for (int j = i; j <= N; ++j)
        {
            if (sum[i][j] > m)
                m = sum[i][j];
        }
    }
    return m;
}

int main()
{
    int n;
    cin >> n;
    int A[n];
    for (int i = 0; i != n; ++i)
        cin >> A[i];
    
    cout << AMax(A, n-1);
    return 0;
}
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
伊谢尔伦
int main()
{
    int n;
    cin >> n;
    int A[n];
    for (int i = 0; i != n; ++i)
        cin >> A[i];    //就算支持 VLA,然而这个循环已经越界了
    
    cout << AMax(A, n-1);
    return 0;
}

If you change the code, please upload your latest code and NA errors.
You can also refer to my code

巴扎黑

Hello, when you define an array, you cannot write it as int A[n], because the compiler needs to open up a certain space for the array when compiling. Your n is a variable, and the specific value can only be obtained when running. If you are wrong locally, it may be due to your compiler. Maybe you are using g++ or something. If you use vs, you will definitely get an error, so you cannot write it like this

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template