#45 Maximum Subarray Difference

題目描述:

Given an array with integers.

Find two non-overlapping subarrays A and B, which|SUM(A) - SUM(B)| is the largest.

Return the largest difference.

 Notice

The subarray should contain at least one number

Example

For [1, 2, -3, 1], return 6.

Challenge 

O(n) time and O(n) space.

題目思路:

這題還是用forward-backward traversal的想法,left類vector算出i以左subarray的最大sum和最小sum,right類vector算出i以右subarray的最大sum和最小sum。然後重新遍歷array,找出最大difference就可以了。

Mycode(AC = 39ms):

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.size() == 0) {
            return 0;
        }
        
        vector<int> left_min(nums), left_max(nums),
                    right_min(nums), right_max(nums);
                    
        // get the left_min and left_max
        int local_min = nums[0], local_max = nums[0];
        for (int i = 1; i < nums.size(); i++) {
            local_min = min(local_min + nums[i], nums[i]);
            local_max = max(local_max + nums[i], nums[i]);
            
            left_min[i] = min(left_min[i - 1], local_min);
            left_max[i] = max(left_max[i - 1], local_max);
        }
        
        // get the right_min and right_max
        local_min = nums[nums.size() - 1];
        local_max = nums[nums.size() - 1];
        
        for (int i = nums.size() - 2; i >= 0; i--) {
            local_min = min(local_min + nums[i], nums[i]);
            local_max = max(local_max + nums[i], nums[i]);
            
            right_min[i] = min(right_min[i + 1], local_min);
            right_max[i] = max(right_max[i + 1], local_max);
        }
        
        // get the max diff
        int diff = 0;
        for (int i = 1; i < nums.size(); i++) {
            diff = max(abs(right_max[i] - left_min[i - 1]), 
                       max(diff, abs(right_min[i] - left_max[i - 1])));
        }
        
        return diff;
    }
};


發佈了221 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章