Leetcode maximum subarray

Source: Internet
Author: User
class Solution {public:    int maxSubArray(int A[], int n) {        int cur_sum = 0;        int max_sum = INT_MIN;                for (int i=0; i<n; i++) {            cur_sum += A[i];            if (cur_sum > max_sum) max_sum = cur_sum;            if (cur_sum < 0) {                cur_sum = 0;            }        }        return max_sum;    }};

Old question

Divide and conquer, nlogn, but TLE

class Solution {public:int maxSubArray(int A[], int n) {        return dfs(A, 0, n);    }        int dfs(int A[], int start, int end) {        if (start >= end) {            cout<<"range error: start="<<start<<", end="<<end<<endl;            return INT_MIN;        }        if (start + 1 == end) return A[start];        int mid = (start + end) / 2;        int ma = dfs(A, start, mid);        int mb = dfs(A, mid, end);        int maxsum = ma > mb ? ma : mb;        int lsum = 0, rsum = 0;        int lmax = INT_MIN, rmax = INT_MIN;                for (int i=mid - 1; i>=0; i--) {            lsum += A[i];            if (lsum > lmax) lmax = lsum;        }                for (int i=mid; i<end; i++) {            rsum += A[i];            if (rsum > rmax) rmax = rsum;        }                if (lmax + rmax > maxsum) maxsum = lmax + rmax;        return maxsum;    };};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.