1. 程式人生 > >LeetCode 53. Maximum Subarray--Divide and Conquer(分治法)

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<int>& 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<int> nums1(nums.begin()+tari,nums.begin()+tarj);  
        int result3 = maxSubArray(nums1);
        return max(max(result1, result2), result3);
    }
};