- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximum_Subarray.java
More file actions
Latest commit
35 lines (34 loc) · 945 Bytes
/
Copy pathMaximum_Subarray.java
File metadata and controls
35 lines (34 loc) · 945 Bytes
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
packagecom.leet_code;
publicclassMaximum_Subarray {
publicstaticvoidmain(String[] args) {
int[] arr={-2,1,-3,4,-1,2,1,-5,4};
System.out.println(maxSubArray2(arr));
}
publicstaticintmaxSubArray(int[] nums) {
if (nums.length == 1) {
returnnums[0];
}
intmax=0;
inta=Integer.MIN_VALUE;
for (inti = 0; i < nums.length ; i++) {
intq=0;
while (q!=i+1){
for (intj = q; j <= i; j++) {
max+=nums[j];
}
q++;
if(a<=max){a=max;}max=0;
}
}
returna;
}
publicstaticintmaxSubArray2(int[] nums) {
intmax = nums[0];
inta = nums[0];
for (inti = 1; i < nums.length; i++) {
a = Math.max(nums[i], nums[i] + a);
max = Math.max(a, max);
}
returnmax;
}
}