-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxSubarray.java
More file actions
73 lines (65 loc) · 2.39 KB
/
maxSubarray.java
File metadata and controls
73 lines (65 loc) · 2.39 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
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.
*/
public class Solution {
public int maxSubArray(int[] A) {
if(A==null || A.length==0) return 0;
int result=A[0], curr=A[0];
for(int i=1; i<A.length; i++){
if(curr>=0){ // if curr>=0, then result might be lager. Take curr as condition instead of A[i].
curr+=A[i];
}else{
curr=A[i];
}
result=Math.max(curr, result);
}
return result;
}
}
// The following solutions come from Tao Hu.
// 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)));
}
}