Skip to content

Commit 5839ac2

Browse files
authored
Update 053. Maximum Subarray.java
1 parent db21568 commit 5839ac2

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

053. Maximum Subarray.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,40 @@ public int maxSubArray(int[] nums) {
4242
}
4343
}
4444
}
45+
46+
47+
// improvement, still failed
48+
49+
public class Solution {
50+
public int sum(int[] nums) {
51+
int sum = 0;
52+
for (int i = 0; i < nums.length; i++) {
53+
sum += nums[i];
54+
}
55+
return sum;
56+
}
57+
58+
public int helper(int[] nums) {
59+
int max = sum(nums);
60+
61+
for (int div = 1; div <= nums.length - 1; div++) {
62+
int val = Math.max(helper(Arrays.copyOfRange(nums, 0, div)),
63+
helper(Arrays.copyOfRange(nums, div, nums.length)));
64+
if (val >= max) {
65+
max = val;
66+
}
67+
}
68+
69+
return max;
70+
}
71+
72+
public int maxSubArray(int[] nums) {
73+
if (nums.length == 0) {
74+
return 0;
75+
} else if (nums.length == 1) {
76+
return nums[0];
77+
} else {
78+
return helper(nums);
79+
}
80+
}
81+
}

0 commit comments

Comments
 (0)