-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximum_Subarray.java
More file actions
35 lines (34 loc) · 945 Bytes
/
Maximum_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
package com.leet_code;
public class Maximum_Subarray {
public static void main(String[] args) {
int[] arr={-2,1,-3,4,-1,2,1,-5,4};
System.out.println(maxSubArray2(arr));
}
public static int maxSubArray(int[] nums) {
if (nums.length == 1) {
return nums[0];
}
int max=0;
int a=Integer.MIN_VALUE;
for (int i = 0; i < nums.length ; i++) {
int q=0;
while (q!=i+1){
for (int j = q; j <= i; j++) {
max+=nums[j];
}
q++;
if(a<=max){a=max;}max=0;
}
}
return a;
}
public static int maxSubArray2(int[] nums) {
int max = nums[0];
int a = nums[0];
for (int i = 1; i < nums.length; i++) {
a = Math.max(nums[i], nums[i] + a);
max = Math.max(a, max);
}
return max;
}
}