Maximum Subarray 連續子陣列最大和

範長法@三月軟體發表於2014-10-29

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.

此題為經典的求連續子陣列最大和問題,除了暴力的解法,想辦法用O(n)時間來做。

直接貼程式碼:

 1 class Solution {
 2 public:
 3     int maxSubArray(int A[], int n) {
 4         if(A == NULL || n < 1)
 5             return -1;
 6             
 7         int max = A[0];
 8         int temp = 0;
 9         
10         for(int i = 0 ; i < n ; i++){
11             if(temp < 0)
12                 temp = A[i];
13             else
14                 temp += A[i];
15                 
16             if(temp > max)
17                 max = temp;
18         }
19         
20         return max;
21         
22     }
23 };

 

相關文章