LeetCode OJ平台上Maximum Subarray題目O(n)複雜度解決方式

來源:互聯網
上載者:User

標籤:blog   java   io   2014   art   for   

原始題目例如以下,意為尋找數組和最大的子串,返回這個最大和就可以。

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).

在木易先森的指導下,有一個極其簡單的O(n)複雜度的方法:

-    先找出數組max值,假設max小於0 ,啥也別說了,直接返回max.

-    設定輔助變數currentmax=0;數組從頭至尾掃描一遍

     -    假設currentmax + A[i] <= 0,意味著這個子串對於我們尋找最大和是沒有不論什麼協助的,此時,直接再置currentmax = 0

     -    假設currentmax + A[i] > 0,意味著這個子串的和是有意義的,將這個和跟max比較,時刻保持max的值是當前最理想的最大值

-    最後返回max就可以

源碼例如以下:

public class Solution {    public static int maxSubArray(int[] A) {        if(A.length == 0)            return 0;        int max = A[0];        for(int i = 0; i < A.length; i ++)            if(A[i] > max)                max = A[i];        if(max <= 0)            return max;        int currentmax = 0;        for(int i = 0;i < A.length; i ++){        currentmax += A[i];        if(currentmax <= 0){        currentmax = 0;        continue;        }        else{        if(currentmax > max)        max = currentmax;        }        }        return max;        }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.