1. 程式人生 > >[leetcode]Maximum Subarray

[leetcode]Maximum Subarray

-- htm cout 分治 pan clas body ews array

問題描寫敘述:

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.


基本思路:

遍歷並記錄最大的subarray值。O(n)時間算法


代碼:

int maxSubArray(int A[], int n) {  //C++
        int max = A[0];
        int tmp = 0;
        for(int i = 0; i < n; i++)
        {
            tmp += A[i];
            if(tmp > max)
                max = tmp;    
            if(tmp < 0){
                tmp = 0;
            }
        }
        return max;
    }


分治法

int divideConquer(int A[], int low, int high){  //C++
        if(low == high)
            return A[low];
        
        int mid = (low + high)/2;
        int sum1 = divideConquer(A, low , mid);
        int sum2 = divideConquer(A, mid+1, high);
        int sum3 = findMidMax(A,low,high,mid);
        
        int max;
        max = (sum1 > sum2)? sum1:sum2;
        max = (max > sum3)?

max: sum3; // cout << low << high << mid <<max; return max; } int findMidMax(int A[] , int low , int high, int mid){ int max = A[mid],tmp = 0,sum = 0; int i = mid; while(i >= low ) { tmp +=A[i]; if(tmp > max) max = tmp; i--; } sum = max; max = 0 , tmp = 0; int j = mid+1; while(j <= high) { tmp +=A[j]; if(tmp > max) max = tmp; j++; } sum += max; return sum; } int maxSubArray(int A[], int n) { return divideConquer(A,0,n-1); }





[leetcode]Maximum Subarray