[LeetCode 题解]: Maximum Subarray

前言

 

【LeetCode 题解】系列传送门:  http://www.cnblogs.com/double-win/category/573499.html

 

1.题目描述

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.

2. 解法

 1 class Solution {
 2 public:
 3     int maxSubArray(int A[], int n) {
 4         int sum,ans,i,mark=0;
 5         sum=ans=i=0;
 6         
 7         for(i=0;i<n;i++)
 8            if(A[i]>=0) mark=1;
 9         
10         if(mark==0)
11         {
12             ans=A[0];
13             for(i=1;i<n;i++)
14                if(A[i]>ans) ans=A[i];
15             
16         }
17         else
18         {
19             for(i=0;i<n;i++)
20             {
21                sum+=A[i];
22                if(sum<0)
23                    sum=0;
24                if(sum>ans) ans=sum;
25             }
26         }
27         return ans;        
28     }
29 };

3. 相关题目

Gas Station 题解 http://www.cnblogs.com/double-win/p/3746637.html

作者:Double_Win

出处:   http://www.cnblogs.com/double-win/p/3746672.html

声明: 由于本人水平有限,文章在表述和代码方面如有不妥之处,欢迎批评指正~

posted @ 2014-05-22 22:56  Double_win  阅读(208)  评论(0编辑  收藏  举报