[LintCode]Maximum Subarray Difference

Solving this question by O(n) time w/ O(n) space. The basic idea is to find a appropriate cut let the difference become largest.
We keep track local max, local min, left max, left min, and right min, right max.

class Solution {
public:
    /** * @param nums: A list of integers * @return: An integer indicate the value of maximum difference between two * Subarrays */
    int maxDiffSubArrays(vector<int> nums) {
        // write your code here
        if(nums.empty()) return 0;
        int n = nums.size(), localMax = 0, localMin = 0, res = INT_MIN;
        vector<int> leftMax(n,0);
        vector<int> leftMin(n,0);
        for(int i = 0; i<n; ++i){
            localMax = max(nums[i], nums[i] + localMax);
            localMin = min(nums[i], nums[i] + localMin);
            if(i == 0){
                leftMax[i] = localMax;
                leftMin[i] = localMin;
            }else{
                leftMax[i] = max(leftMax[i-1], localMax);
                leftMin[i] = min(leftMin[i-1], localMin);
            }
        }
        localMax = 0, localMin = 0;
        int rightMax = 0, rightMin = 0;
        for (int i = n-1; i>0; --i) {
            localMax = max(nums[i]+localMax, nums[i]);
            localMin = min(nums[i] + localMin, nums[i]);
            if(i == n-1){
                rightMax = localMax;
                rightMin = localMin;
            }else{
                rightMax = max(localMax, rightMax);
                rightMin = min(localMin, rightMin);
            }
            res = max(res, max(abs(rightMax - leftMin[i-1]),abs(leftMax[i-1]-rightMin)));
        }
        return res;
    }
};

你可能感兴趣的:(lintcode)