Skip to content

Commit 02e3ac8

Browse files
committed
add: MaximumSubarraySumDp
1 parent a0ef62f commit 02e3ac8

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
public class MaximumSubarraySumDp {
2+
public int maximumSubarraySumDp(int[] nums) {
3+
int n = nums.length;
4+
if (n == 0) {
5+
return 0;
6+
}
7+
int[] dp = new int[n];
8+
// Base case: the maximum subarray sum of an array with just one
9+
// element is that element.
10+
dp[0] = nums[0];
11+
int maxSum = dp[0];
12+
// Populate the rest of the DP array.
13+
for (int i = 1; i < n; i++) {
14+
// Determine the maximum subarray sum ending at the current
15+
// index.
16+
dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]);
17+
maxSum = Math.max(maxSum, dp[i]);
18+
}
19+
return maxSum;
20+
}
21+
}

0 commit comments

Comments
 (0)