给定一个整数数组,找出两个不重叠的子数组A和B,使两个子数组和的差的绝对值|SUM(A) - SUM(B)|最大。
// max_vec[i] : the max value of the consecutive sum from [0 ...i]
void func(vector<int>& max_vec, vector<int>& min_vec, vector<int>& nums) {
int max_sum = nums[0];
int min_sum = nums[0];
for (int i = 1; i < nums.size(); ++i) {
max_vec[i] = max(max_vec[i], max_vec[i - 1]);
if (max_sum <= 0) {
max_sum = nums[i];
} else {
max_sum += nums[i];
}
max_vec[i] = max(max_vec[i], max_sum);
min_vec[i] = min(min_vec[i], min_vec[i - 1]);
if (min_sum > 0) {
min_sum = nums[i];
} else {
min_sum += nums[i];
}
min_vec[i] = min(min_vec[i], min_sum);
}
}
int maxDiffSubArrays(vector<int> nums) {
// write your code here
vector<int> max_l2r(nums), min_l2r(nums);
func(max_l2r, min_l2r, nums);
reverse(nums.begin(), nums.end());
vector<int> max_r2l(nums), min_r2l(nums);
func(max_r2l, min_r2l, nums);
reverse(max_r2l.begin(), max_r2l.end());
reverse(min_r2l.begin(), min_r2l.end());
int ret = 0;
for (int i = 1; i < nums.size(); ++i) {
ret = max(ret, abs(max_l2r[i - 1] - min_r2l[i]));
ret = max(ret, abs(min_l2r[i - 1] - max_r2l[i]));
}
return ret;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。