您的位置:首页 > 编程语言

网易实习生算法组编程题二:求数组的两个子数组和的最大值

2017-03-27 10:36 267 查看
求一个正整数数组的两个子数组,使其和相等,找出满足这样要求的子数组和的最大值,若不存在,则返回-1。比如【1,1,2,3,5,20】,结果为6。

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;

const int maxn = 500010;
int n;
vector<int> a;
int dp[2][maxn];
int solve(vector<int> v) {
    int res = 0;
    memset(dp, 0, sizeof(dp));
    int p = 0;
    for (int i = 0; i < v.size(); i++) {
        //for each loop, dp[p][ix] stores the large sum of two subarray where the substract is equal to ix
        dp[p][v[i]] = max(dp[1 - p][v[i]], v[i]);
        for (int ix = 0; ix < maxn; ix++) {
            if (dp[1 - p][ix]) {//zero means that for "ix",there is no two subarray.
                // do not use the v[i] element
                if (dp[p][ix] < dp[1 - p][ix]) dp[p][ix] = dp[1 - p][ix];
                //put the v[i] element to the bigger subArray
                dp[p][ix + v[i]] = max(dp[p][ix + v[i]], max(dp[1 - p][ix + v[i]], dp[1 - p][ix] + v[i]));
                //put the v[i] element to the smaller subArray
                dp[p][abs(ix - v[i])] = max(dp[p][abs(ix - v[i])], max(dp[1 - p][abs(ix - v[i])], max(dp[1 - p][ix] - ix + v[i], dp[1 - p][ix])));
            }
        }
        p = 1 - p;
    }
    if (dp[1 - p][0]) res = dp[1 - p][0];
    else res = -1;
    return res;
}
int main() {
    cin >> n;
    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;
        a.push_back(x);
    }
    cout << solve(a) << endl;
    return 0;
}		a.push_back(x);
}
cout << solve(a) << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: