1
+ package MaximumSubarray ;
2
+
3
+ /**
4
+ * User: Danyang
5
+ * Date: 1/22/2015
6
+ * Time: 20:49
7
+ *
8
+ * Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
9
+
10
+ For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
11
+ the contiguous subarray [4,−1,2,1] has the largest sum = 6.
12
+
13
+ More practice:
14
+ If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
15
+
16
+ */
17
+ public class Solution {
18
+ /**
19
+ * O(n) iterative is trivial
20
+ * Divide and Conquer Approach
21
+ * O(n lgn)
22
+ * 1. divide in half
23
+ * 2. left max sub
24
+ * 3. right max sub
25
+ * 4. max sub crossing the middle point
26
+ * @param A
27
+ * @return
28
+ */
29
+ public int maxSubArray (int [] A ) {
30
+ return maxSubArray (A , 0 , A .length );
31
+ }
32
+
33
+ int maxSubArray (int [] A , int s , int e ) {
34
+ if (s >=e )
35
+ return Integer .MIN_VALUE ;
36
+ if (s ==e -1 )
37
+ return A [s ];
38
+
39
+ int m = (s +e )/2 ;
40
+ int l = maxSubArray (A , s , m );
41
+ int r = maxSubArray (A , m , e );
42
+ int c = maxCross (A , s , e , m );
43
+ return Math .max (Math .max (l , r ), c );
44
+ }
45
+
46
+ int maxCross (int [] A , int s , int e , int m ) {
47
+ int max_l = A [m ];
48
+ int max_r = A [m ];
49
+
50
+ int acc = A [m ];
51
+ for (int i =m -1 ; i >=s ; i --) {
52
+ acc += A [i ];
53
+ max_l = Math .max (max_l , acc );
54
+ }
55
+ acc = A [m ];
56
+ for (int i =m +1 ; i <e ; i ++) {
57
+ acc += A [i ];
58
+ max_r = Math .max (max_r , acc );
59
+ }
60
+ return max_l +max_r -A [m ];
61
+ }
62
+ }
0 commit comments