forked from walnutown/CodingInTheDeep
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximumSubarray.java
More file actions
56 lines (51 loc) · 2.04 KB
/
Copy pathMaximumSubarray.java
File metadata and controls
56 lines (51 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
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.
*/
// http://en.wikipedia.org/wiki/Maximum_subarray_problem
// Kadane's Algorithm (1984)
// Dynamic Programming
// sum -- the max subarray sum ending at current value
// max -- the max subarray sum found so far
// In each day, we check the previous max, if max>0, we add current value to the subarray
// if max<0, we choose current day as a new starting point for subarray
// time: O(n); space: O(1)
public class Solution {
public int maxSubArray(int[] A) {
if (A==null || A.length==0) return 0;
int max = Integer.MIN_VALUE, sum = 0;
for (int i=0; i<A.length; i++){
// if sum+A[i] < A[i], we start a new subarray
sum = Math.max(A[i], sum+A[i]);
max = Math.max(sum, max);
}
return max;
}
}
// Divide and Conquer
// time: O(nlgn); space: O(1)
public class Solution {
public int maxSubArray(int[] A) {
if (A==null || A.length==0) return 0;
return finder(A, 0, A.length-1);
}
public int finder(int[] A, int start, int end){
if (start > end) return Integer.MIN_VALUE;
int mid = start + ((end - start)>>1); // notice here, cannot omit the out-nested brackets
int left=Integer.MIN_VALUE, right=Integer.MIN_VALUE, sum=0;
for (int i=mid+1; i<=end; i++){
sum += A[i];
right = Math.max(sum,right);
}
sum = 0;
for (int i=mid-1; i>=start; i--){
sum += A[i];
left = Math.max(sum, left);
}
int mmax = A[mid] + Math.max(left, 0) + Math.max(right, 0);
return Math.max(mmax, Math.max(finder(A, start, mid-1), finder(A, mid+1, end)));
}
}