leetcode[53]Maximum Subarray

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.

class Solution {

public:

int maxSubArray(int A[], int n) 

{

    int maxTemp=A[0];

    int **temp=new int*[n];

    for (int i=0;i<n;i++)

        temp[i]=new int[2];

    temp[0][0]=0;

    temp[0][1]=A[0];

    int index=0;

    for (int i=1;i<n;i++)

    {

        if(temp[i-1][1]<0)

        {

            temp[i][0]=i;

            temp[i][1]=A[i];

        }

        else

        {

            temp[i][0]=temp[i-1][0];

            temp[i][1]=temp[i-1][1]+A[i];

        }

        if (maxTemp<temp[i][1])

        {

            maxTemp=temp[i][1];

            index=i;

        } 

    }

    vector<int> res;

    for (int i=temp[index][0];i<=index;i++)

        res.push_back(A[i]);

    int ans=temp[index][1];

    for (int i=0;i<n;i++)

        delete temp[i];

    return ans;

}

/*

    int maxSubArray(int A[], int n) {

    int maxTemp=A[0];

    int sum=A[0];

    for (int i=1;i<n;i++)

    {

        sum=sum<0?A[i]:sum+A[i];

        maxTemp=sum>maxTemp?sum:maxTemp;

    }

    return maxTemp;        

    }

*/

};

/*

网易的笔试题中出现了一道之前在网上看过的编程题,早上着手编写测试了一下,题目如下:



给定一整型数字a[]={a[0],...,a[n])},找出连续子串{a[x]),a[x+1],...,a[y]},使得和最大,其中,0<=x<=y<=n。



要求时间复杂度为O(n)



解决思路:

(1)和最大的子串一定是以数组a中的某一个元素为结束,所以我们分别对每一个元素作为当前子串的结尾计算当前和最大的子串,



              再对计算出的所有子串和进行比较,最大的那个就是解。



(2)计算以元素a(i+1)结尾的和最大的子串:假定以a(i)结尾的和最大子串为L[i],和为sum[i],则当sum[i]+a[i+1]>a[i+1],



   那L[i+1]为L[i]加上a[i+1],sum[i+1]=sum[i]+a[i+1];否则L[i+1]为a[i],sum[i+1]=a[i+1];为什么这样?注意“连续”,也就是说



      以a[i+1]结尾的子串必定包含a[i+1],那和最大的子串L[i+1]只能是a[i+1]或者L[i]加上a[i+1],显然,sum[i]+a[i+1]>a[i+1]则不取a[i+1]而



      取L[i]加上a[i+1],否则就取a[i+1];

*/

 

你可能感兴趣的:(LeetCode)