[leetcode] Maximum Subarray

來源:互聯網
上載者:User

標籤:style   class   blog   code   java   http   

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.

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.

https://oj.leetcode.com/problems/maximum-subarray/

思路1:Kadane演算法,複雜度O(n)。

思路2:分治。對於每次遞迴,將數組分半,最大和可能存在

  1. 完全在左面部分(遞迴求解)
  2. 完全在右面部分(遞迴求解)
  3. 橫跨左右兩個部分(從中間(必須包含中間元素,否則左右無法串連)向兩邊加,記錄最大值)

注意點:注意負數的處理,此題最大值為負數時依然返回最大的負數,也有題目負數時要求返回0。注意兩種情況下最大值的初始化等細節的區別。

 

思路1代碼:

public class Solution {public int maxSubArray(int[] A) {int n = A.length;int i;int maxSum = A[0];int thisSum = 0;for (i = 0; i < n; i++) {thisSum += A[i];if (thisSum > maxSum)maxSum = thisSum;if (thisSum < 0)thisSum = 0;}return maxSum;}public static void main(String[] args) {System.out.println(new Solution().maxSubArray(new int[] { -2, 1, -3, 4,-1, 2, 1, -5, 4 }));}}

思路2代碼:

public class Solution {    public int maxSubArray(int[] A) {        return maxSub(A, 0, A.length - 1);    }    private int maxSub(int[] a, int left, int right) {        if (left == right)            return a[left];        int mid = (left + right) / 2;        int maxLeft = maxSub(a, left, mid);        int maxRight = maxSub(a, mid + 1, right);        int leftHalf = 0, leftHalfMax = Integer.MIN_VALUE;        int rightHalf = 0, rightHalfMax = Integer.MIN_VALUE;        for (int i = mid; i >= left; i--) {            leftHalf += a[i];            if (leftHalf > leftHalfMax)                leftHalfMax = leftHalf;        }        for (int i = mid + 1; i <= right; i++) {            rightHalf += a[i];            if (rightHalf > rightHalfMax)                rightHalfMax = rightHalf;        }        return Math.max(Math.max(maxLeft, maxRight), (leftHalfMax + rightHalfMax));    }    public static void main(String[] args) {        System.out.println(new Solution().maxSubArray(new int[] { -2, -1, -3, -2, -5 }));    }}
參考:

Data Structures and Algorithm Analysis in C

http://blog.csdn.net/xshengh/article/details/12708291

 

聯繫我們

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