[leetcode.com]算法题目 - 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.

 1 class Solution {
 2 public:
 3     int maxSubArray(int A[], int n) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if (0>=n) return 0;
 7               
 8         int b = 0;
 9         
10         int sum =A[0];
11         
12         for(int i=0;i<n;i++){
13             if(b<0)
14                 b=0;
15                 
16             b = b+A[i];
17             
18             if(b>sum)
19                 sum =b;
20         }
21         return sum;
22     }
23 };
我的答案

思路:最大连续子数组的和,这是个非常经典的题目,答案也很简练,重点是代码中b这个变量的使用。

posted on 2013-09-11 22:27  Horstxu  阅读(201)  评论(0编辑  收藏  举报

导航