Skip to content

Commit db21568

Browse files
authored
Create 053. Maximum Subarray.java
1 parent 267f5c6 commit db21568

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

053. Maximum Subarray.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
//
2+
3+
// Time limit exceeded version
4+
public class Solution {
5+
public int check(int[] nums, int divider) {
6+
int lSum = 0, rSum = 0;
7+
for (int i = 0; i < divider; i++) {
8+
lSum += nums[i];
9+
}
10+
for (int i = divider; i < nums.length; i++) {
11+
rSum += nums[i];
12+
}
13+
if (divider == 0) {
14+
return rSum;
15+
} else {
16+
return Math.max(lSum, rSum);
17+
}
18+
}
19+
20+
public int helper(int[] nums) {
21+
int max = check(nums, 0);
22+
23+
for (int div = 1; div <= nums.length - 1; div++) {
24+
int val = Math.max(check(nums, div),
25+
Math.max(helper(Arrays.copyOfRange(nums, 0, div)),
26+
helper(Arrays.copyOfRange(nums, div, nums.length))));
27+
if (val >= max) {
28+
max = val;
29+
}
30+
}
31+
32+
return max;
33+
}
34+
35+
public int maxSubArray(int[] nums) {
36+
if (nums.length == 0) {
37+
return 0;
38+
} else if (nums.length == 1) {
39+
return nums[0];
40+
} else {
41+
return helper(nums);
42+
}
43+
}
44+
}

0 commit comments

Comments
 (0)