Maximum Subarray

难度:4

最大子段和,本来是打算用单调队列写的

看到这句

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.

玛雅还有分治法可以做,看了一下,空间复杂度比单调队列少

Kadane算法

详见:http://blog.csdn.net/joylnwang/article/details/6859677

讲的很详细,不过这博客里的代码写的略臃肿

以下是我的代码,只有两个变量,很好理解的吧

class Solution 
{
public:
    int maxSubArray(int A[], int n) 
	{
		int ans=-0x3fffffff;
		int cur_sum=0;
		for(int i=0;i<n;i++)
		{
			ans=max(ans,A[i]);
			if(A[i]+cur_sum<0)
			{
				cur_sum=0;
			}
			else
			{
				cur_sum+=A[i];
				ans=max(ans,cur_sum);
			}
		}
		return ans;
    }
};


你可能感兴趣的:(Maximum Subarray)