标签:
A variantion to "largest\smallest consecutive subarray". Idea is, at position i, the current max diff is max(max_left[i] - min_right[i+1], max_right[i + 1] - min_left[i]). Yes you can see boiler-plate code below. I‘m lazy to make it shorter now.
class Solution { void largest_l2r(vector<int> &A, vector<int> &ret) { size_t len = A.size(); ret.resize(len); int csum = A[0], sofar = A[0]; ret[0] = A[0]; for (int i = 1; i < len; i++) { int nsum = csum + A[i]; if (A[i] > nsum) { csum = A[i]; } else { csum = nsum; } sofar = max(sofar, csum); ret[i] = sofar; } } void smallest_l2r(vector<int> &A, vector<int> &ret) { size_t len = A.size(); ret.resize(len); int csum = A[0], sofar = A[0]; ret[0] = A[0]; for (int i = 1; i < len; i++) { int nsum = csum + A[i]; if (A[i] < nsum) { csum = A[i]; } else { csum = nsum; } sofar = min(sofar, csum); ret[i] = sofar; } } void largest_r2l(vector<int> &A, vector<int> &ret) { size_t len = A.size(); ret.resize(len); int csum = A.back(), sofar = A.back(); ret[len - 1] = A.back(); for (int i = len - 2; i >= 0; i --) { int nsum = csum + A[i]; if (A[i] > nsum) { csum = A[i]; } else { csum = nsum; } sofar = max(sofar, csum); ret[i] = sofar; } } void smallest_r2l(vector<int> &A, vector<int> &ret) { size_t len = A.size(); ret.resize(len); int csum = A.back(), sofar = A.back(); ret[len - 1] = A.back(); for (int i = len - 2; i >= 0; i --) { int nsum = csum + A[i]; if (A[i] < nsum) { csum = A[i]; } else { csum = nsum; } sofar = min(sofar, csum); ret[i] = sofar; } } public: /** * @param nums: A list of integers * @return: An integer indicate the value of maximum difference between two * Subarrays */ int maxDiffSubArrays(vector<int> nums) { vector<int> max_l2r, max_r2l; largest_l2r(nums, max_l2r); largest_r2l(nums, max_r2l); vector<int> min_l2r, min_r2l; smallest_l2r(nums, min_l2r); smallest_r2l(nums, min_r2l); int ret = INT_MIN; for(int i = 0; i < nums.size() - 1; i ++) { int r1 = max_l2r[i] - min_r2l[i + 1]; int r2 = max_r2l[i + 1] - min_l2r[i]; ret = max(ret, max(r1, r2)); } return ret; } };
LintCode "Maximum Subarray Difference"
标签:
原文地址:http://www.cnblogs.com/tonix/p/4889335.html