Leetcode_num15_Maximun Subarray,leetcode

來源:互聯網
上載者:User

Leetcode_num15_Maximun Subarray,leetcode

題目: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.

click to show more practice.

More practice:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

此題的要求是在給定的數組中找出總和最大的連續數組片段,分別使用o(n)和分而治之的方法。

o(n)的方法比較簡單,即是依次遍曆數組,記錄目前求和值與最大值:若當前數為負數,則計算加上其後的求和值,與最大值進行比較,若大於最大值則更改最大值,其後,將求和值歸零,以下一個值為片段的開始;若當前數非負,則只需比較加上其後的求和值與最大值,若求和值大於最大值,則更改最大值。代碼如下:

class Solution:    # @param A, a list of integers    # @return an integer    def maxSubArray(self, A):        L=len(A)        rs=0        m=A[0]        for i in range(0,L):            rs+=A[i]            if rs<0:                if rs>m:                    m=rs                rs=0            else:                if rs>m:                    m=rs                    return m

divide and conquer的方法,即歸併,演算法複雜度為o(nlogn),計算式為 T(n)=2*T(n/2)+o(n)

採用遞迴調用,以數組片段的中間點為分界線,判斷該中間點是否包括在最終所求的數組片段內,因此需要比較三個值的大小:包含中間點的最大和值,不包含中間點的最大和值(即左數組片段的最大和值,右數組片段的最大和值),選擇其中最大的值作為結果返回。

後兩值採用函數遞迴調用即可得到;

而在求包含中間點的最大和值,需要找到向左延伸的上界和向右延伸的下界。因此,以中間點為起點向左求和,最大值的初始值設為中間點的值,如果當前和值大於最大值,則修改最大值;同理,以中間點右邊一點為起點向右求和,最大值的初始值設為該點的值,如果當前和值大於最大值,則修改最大值,將兩個最大值相加,即可得到包含中間點的最大和值。具體的代碼如下:

class Solution:    # @param A, a list of integers    # @return an integer    def maxSubArray(self, A):        def maxS(A,left,right):            if left==right: return A[left]            middle=(left+right)/2            leftm=maxS(A,left,middle)             rightm=maxS(A,middle+1,right)            lm=A[middle]            rm=A[middle+1]            t=0            for i in range(middle,left-1,-1):                t+=A[i]                if(t>lm):                    lm=t            t=0            for i in range(middle+1,right+1):                t+=A[i]                if(t>rm):                    rm=t            return max(leftm,rightm,lm+rm)                    L=len(A)        return maxS(A,0,L-1)





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.