Skip to content

Commit 57f7d50

Browse files
committed
add: maximumSubarraySum
1 parent 7702738 commit 57f7d50

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)