forked from shogunsea/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaximum-subarray.java
67 lines (56 loc) · 1.78 KB
/
maximum-subarray.java
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
public class Solution {
/**
* @param nums: A list of integers
* @return: A integer indicate the sum of max subarray
*/
public int maxSubArray(ArrayList<Integer> nums) {
// write your code
// brute force O(n^2)
if (nums == null) {
return 0;
}
int max = nums.get(0);
int size = nums.size();
for (int i = 0; i < size; i++) {
int tempSum = nums.get(i);
max = max < tempSum? tempSum : max;
for (int j = i + 1; j < size; j++) {
if (tempSum > 0) {
tempSum += nums.get(j);
max = max < tempSum? tempSum : max;
} else {
break;
}
}
}
return max;
}
}
// O(n) solution.
public class Solution {
/**
* @param nums: A list of integers
* @return: A integer indicate the sum of max subarray
*/
public int maxSubArray(ArrayList<Integer> nums) {
// write your code
if (nums == null) {
return 0;
}
int max = nums.get(0);
int previousSum = max;
int size = nums.size();
// as long as previous sum is positive, it can
// contribute to following subarray. however
// negative values in the folloing subarry
// might decrease the totalsum, so we need to
// update the global sum with possible
// maximal sum.
for (int i = 1; i < size; i++) {
int current = nums.get(i);
previousSum = Math.max(current, current + previousSum);
max = max < previousSum? previousSum : max;
}
return max;
}
}