2018头条笔试题数组遍历

原题:https://www.nowcoder.com/question/next?pid=8537290&qid=141067&tid=17473994

给定一个数组序列, 需要求选出一个区间, 使得该区间是所有区间中经过如下计算的值最大的一个:

区间中的最小数 * 区间所有数的和最后程序输出经过计算后的最大值即可,不需要输出具体的区间。如给定序列 [6 2 1]则根据上述公式, 可得到所有可以选定各个区间的计算值:

[6] = 6 * 6 = 36;

[2] = 2 * 2 = 4;

[1] = 1 * 1 = 1;

[6,2] = 2 * 8 = 16;

[2,1] = 1 * 3 = 3;

[6, 2, 1] = 1 * 9 = 9;

从上述计算可见选定区间 [6] ,计算值为 36, 则程序输出为 36。

区间内的所有数字都在[0, 100]的范围内;

输入描述:
第一行输入数组序列长度n,第二行输入数组序列。
对于 50%的数据, 1 <= n <= 10000;
对于 100%的数据, 1 <= n <= 500000;

输出描述:
输出数组经过计算后的最大值。

输入例子1:
3
6 2 1

输出例子1:
36

#include <bits/stdc++.h>
// https://www.nowcoder.com/question/next?pid=8537290&qid=141067&tid=17473994
using namespace std;
#define M(a, b) memset(a,b,sizeof(a))
typedef long long LL;
// memset(a,0x3f,sizeof(a))
//memset(a,0xcf,sizeof(a))
const int maxn = 3002;

//
// 第一行输入数组序列长度n,第二行输入数组序列。
// 对于 50%的数据,  1 <= n <= 10000;
//对于 100%的数据, 1 <= n <= 500000;
//时间限制:3秒
//
//空间限制:131072K
// 注意内存限制, 定义一个二维数组 m_min[500000][500000] 会内存溢出
// 131072K 能放 33554432 个int 数,但 二维数组需要存 891896832 个数
int main() {

    cout << 32768 * 1024 / sizeof(int) << endl;
    cout << 131072 * 1024 / sizeof(int) << endl; // 33554432

    cout << 500000 * 500000 << endl;              // 891896832

    int n;
    cin >> n;
    int nums[n + 1];
    for (int i = 1; i <= n; i++) {
        cin >> nums[i];
    }

    int cur_min;
    int ans = nums[1] << 1;
    for (int i = 1; i <= n; i++) {
        cur_min = nums[i]; // 以当前的数为最小值,两端扩展遍历法 
        int sum = nums[i];
        for (int j = i - 1; j >= 1; j--) {
            if (nums[j] >= cur_min) {
                sum += nums[j];
            } else {
                break;
            }
        }

        for (int j = i + 1; j <= n; j++) {
            if (nums[j] >= cur_min) {
                sum += nums[j];
            } else {
                break;
            }
        }
        ans = max(ans, cur_min * sum);
    }
    cout << ans << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lilele12211104/article/details/81587416