Skip to content

Commit 2c4d363

Browse files
左程云左程云
authored andcommitted
modify code on class
1 parent 244b6ae commit 2c4d363

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/topinterviewquestions/Problem_0053_MaximumSubarray.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,48 @@
22

33
public class Problem_0053_MaximumSubarray {
44

5+
public static int maxSum(int[] nums) {
6+
int N = nums.length;
7+
// dp[i] 含义:子数组必须以i结尾的时候,所有可以得到的子数组中,最大累加和是多少?
8+
int[] dp = new int[N];
9+
dp[0] = nums[0];
10+
int max = Integer.MIN_VALUE;
11+
for (int i = 1; i < N; i++) {
12+
int p1 = nums[i];
13+
int p2 = nums[i] + dp[i - 1];
14+
dp[i] = Math.max(p1, p2);
15+
max = Math.max(max, dp[i]);
16+
}
17+
return max;
18+
}
19+
20+
public static int maxSumFollowUp(int[] arr) {
21+
if (arr == null) {
22+
return 0;
23+
}
24+
int N = arr.length;
25+
if (N == 0) {
26+
return 0;
27+
}
28+
if (N == 1) {
29+
return arr[0];
30+
}
31+
if (N == 2) {
32+
return Math.max(arr[0], arr[1]);
33+
}
34+
// N > 2
35+
int[] dp = new int[N];
36+
dp[0] = arr[0];
37+
dp[1] = Math.max(arr[0], arr[1]);
38+
for (int i = 2; i < N; i++) {
39+
int p1 = arr[i];
40+
int p2 = dp[i - 1];
41+
int p3 = arr[i] + dp[i - 2];
42+
dp[i] = Math.max(Math.max(p1, p2), p3);
43+
}
44+
return dp[N-1];
45+
}
46+
547
public static int maxSubArray(int[] nums) {
648
int cur = 0;
749
int max = Integer.MIN_VALUE;

src/topinterviewquestions/Problem_0062_UniquePaths.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ public static int uniquePaths(int m, int n) {
1717
return (int)o1;
1818
}
1919

20+
// 调用的时候,请保证初次调用时,m和n都不为0
2021
public static long gcd(long m, long n) {
2122
return n == 0 ? m : gcd(n, m % n);
2223
}

0 commit comments

Comments
 (0)