leetcode 24th round

來源:互聯網
上載者:User

標籤:style   blog   color   io   os   ar   for   div   sp   

public class Solution {    public int maxSubArray(int[] A) {              return totalMax(A, 0, A.length-1);           }        public int totalMax(int[] A, int low, int high)    {        if(low == high)        {            return A[low];        }        int mid = (low+high)/2;        int leftMax = totalMax(A, low, mid);        int rightMax = totalMax(A, mid+1, high);        int crossMax = MidMax(A, low, mid, high);        if((leftMax > rightMax) && (leftMax > crossMax))        {            return leftMax;        }        else if ((rightMax > leftMax) && (rightMax > crossMax))        {            return rightMax;        }        else        {            return crossMax;        }            }        public int MidMax(int[] A, int low, int mid, int high)    {        int left_sum = Integer.MIN_VALUE;        int sum = 0;        int left_ind = mid;        for(int i = mid; i >= low; i--)        {            sum = sum + A[i];            if(sum > left_sum)            {                left_sum = sum;                left_ind = i;            }        }        int right_sum = Integer.MIN_VALUE;        sum = 0;        int right_ind = mid;        for (int i = mid+1; i <= high; i++)        {            sum = sum + A[i];            if(sum > right_sum)            {                right_sum = sum;                right_ind = i;            }        }        return (left_sum + right_sum);    }}

 

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.

 

這道題的解我沒有想出來,但隱約覺得應該是dynamic programming

我為自己感到羞愧,這道題是演算法書上的原題!這道題被用來講divide and conquer方法

solution:from beginning to i, find the contiguous subarray ending with i which has the largest sum

public class Solution {    public int maxSubArray(int[] A) {                int max = A[0];        int[] sum = new int[A.length];        sum[0] = A[0];         for (int i = 1; i < A.length; i++) {            sum[i] = Math.max(A[i], sum[i - 1] + A[i]);            max = Math.max(max, sum[i]);        }         return max;            }}

這個解法的複雜度是O(n)

More practice: divide and conquer

 

leetcode 24th round

聯繫我們

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