We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 7702738 commit 57f7d50Copy full SHA for 57f7d50
java/Dynamic Programming/MaximumSubarraySum.java
@@ -0,0 +1,19 @@
1
+public class MaximumSubarraySum {
2
+ public int maximumSubarraySum(int[] nums) {
3
+ if (nums == null || nums.length == 0) {
4
+ return 0;
5
+ }
6
+ // Set the sum variables to Integer.MIN_VALUE to ensure negative
7
+ // sums can be considered.
8
+ int maxSum = Integer.MIN_VALUE;
9
+ int currentSum = 0;
10
+ // Iterate through the array to find the maximum subarray sum.
11
+ for (int num : nums) {
12
+ // Either add the current number to the existing running sum, or
13
+ // start a new subarray at the current number.
14
+ currentSum = Math.max(currentSum + num, num);
15
+ maxSum = Math.max(maxSum, currentSum);
16
17
+ return maxSum;
18
19
+}
0 commit comments