-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxSubArray.java
More file actions
41 lines (39 loc) · 1.06 KB
/
maxSubArray.java
File metadata and controls
41 lines (39 loc) · 1.06 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
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class maxSubArray {
public int maxSubArray(int[] nums) {
Integer max=nums[0];
Integer sum=nums[0];
//method one
for (Integer i=1;i<nums.length;i++){
sum=Math.max(sum+nums[i],nums[i]);
max=Math.max(sum,max);
}
//method two
for(Integer i=1;i<nums.length;i++){
if(sum>0){
sum=sum+nums[i];
}
else {
sum = nums[i];
}
max=Math.max(sum,max);
}
//method three
List<Integer> sumList = new ArrayList();
sumList.add(nums[0]);
for (Integer i=1;i<nums.length;i++){
if(sumList.get(i-1)>0) {
Integer newItem=nums[i]+sumList.get(i-1);
sumList.add(newItem);
}
else{
sumList.add(nums[i]);
}
}
max= Collections.max(sumList);
return max;
}
}