LeetCode 53. Maximum Subarray--Divide and Conquer(分治法)

题目链接

53. Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.


解:最简单的思路是遍历每一段的和,时间复杂度是O(n^2),优化了之后还是不能通过最后一个测试样例,超时,于是只能换一种思路了:

1.首先从左到右遍历数组,并记录一个[0,x]的和,如果计算的和相比之前的和大,那么就用大的和替换之前的和,并记录当前的x值(tari),遍历结束时,所得到的tari的意义就是所求最大子数组如果是[0,tari]的子数组,其右边界一定是tari

2.从右到左遍历数组,同理得到一个tarj

3.如果tari >= tarj,易知所求子数组一定是[tarj, tari]

4.若tari < tarj,所求子数组一定在[0,tari],[tari,tarj],[tarj,size-1]中,再分别用同样的方法求得三个最大和,取其中最大值

代码:

class Solution {
public:
    int maxSubArray(vector& nums) {
        int i, j;
        int tari, tarj;
        int size = nums.size();
        int sum = -2147483648;
        int temp = 0;
        for (i = 0; i < size; i++) {
            temp += nums[i];
            if (temp > sum) {
                sum = temp;
                tari = i;		
            }
        }
        temp = 0;
        sum = -2147483648;
        for (i = size-1; i >= 0; i--) {
            temp += nums[i];
            if (temp > sum) {
                sum = temp;
                tarj = i;		
            }
        }
        if (tari >= tarj) {
        	int result = 0;
        	for (j = tarj; j <= tari; j++) {
                result += nums[j];
            }
            return result;
        }
        temp = 0;
        int tarii;
        sum = -2147483648;
        for (j = tari; j >=0; j--) {
            temp += nums[j];
            if (temp > sum) {
                sum = temp;
                tarii = j;		
            }
        }
	    int result1 = 0;
        for (j = tarii; j <= tari; j++) result1 += nums[j];
        temp = 0;
        int tarjj;
        sum = -2147483648;
        for (j = tarj; j < size; j++) {
            temp += nums[j];
            if (temp > sum) {
                sum = temp;
                tarjj = j;		
            }
        }
        int result2 = 0;
        for (j = tarj; j <= tarjj; j++) result2 += nums[j];
        vector nums1(nums.begin()+tari,nums.begin()+tarj);  
        int result3 = maxSubArray(nums1);
        return max(max(result1, result2), result3);
    }
};




你可能感兴趣的:(LeetCode)