Skip to content

Commit 534e9a6

Browse files
author
tanfanhua
committed
dp
1 parent de5f3cb commit 534e9a6

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/com/blankj/easy/_0053/Solution.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,5 +44,39 @@ public static void main(String[] args) {
4444
Solution solution = new Solution();
4545
int[] nums0 = new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4};
4646
System.out.println(solution.maxSubArray(nums0));
47+
System.out.println(solution.myMaxSubArray(nums0));
48+
int[] nums1 = new int[]{2, 7, 9, 3, 1};
49+
System.out.println(solution.maxSubArray(nums1));
50+
System.out.println(solution.myMaxSubArray(nums1));
51+
int[] nums2 = new int[]{-2, 11, -9, 3, 1};
52+
System.out.println(solution.maxSubArray(nums2));
53+
System.out.println(solution.myMaxSubArray(nums2));
54+
int[] nums3 = new int[]{-2, 12, -9, 3, 1};
55+
System.out.println(solution.maxSubArray(nums3));
56+
System.out.println(solution.myMaxSubArray(nums3));
57+
}
58+
59+
public int myMaxSubArray(int[] nums) {
60+
if (nums == null || nums.length == 0) {
61+
return Integer.MIN_VALUE;
62+
}
63+
int max = Integer.MIN_VALUE;
64+
int[] f = new int[nums.length];
65+
for (int i = 0; i < nums.length; i++) {
66+
if (i == 0) {
67+
f[i] = nums[i];
68+
} else {
69+
if (f[i - 1] > 0) {
70+
f[i] = f[i-1] + nums[i];
71+
} else {
72+
f[i] = nums[i];
73+
}
74+
}
75+
if (max < f[i]) {
76+
max = f[i];
77+
}
78+
}
79+
80+
return max;
4781
}
4882
}

0 commit comments

Comments
 (0)