Skip to content

Commit bbd6492

Browse files
committed
07/28 maxSubArray sum
1 parent 53ace65 commit bbd6492

1 file changed

Lines changed: 18 additions & 3 deletions

File tree

java/MaximumSumSubArray.java

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,27 @@
1-
public class Solution
1+
/*
2+
this problem was discussed by Jon Bentley (Sep. 1984 Vol. 27 No. 9 Communications of the ACM P885)
3+
4+
the paragraph below was copied from his paper (with a little modifications)
5+
6+
algorithm that operates on arrays: it starts at the left end (element A[1]) and scans through to the right end (element A[n]), keeping track of the maximum sum subvector seen so far. The maximum is initially A[0]. Suppose we've solved the problem for A[1 .. i - 1]; how can we extend that to A[1 .. i]? The maximum
7+
sum in the first I elements is either the maximum sum in the first i - 1 elements (which we'll call MaxSoFar), or it is that of a subvector that ends in position i (which we'll call MaxEndingHere).
8+
9+
MaxEndingHere is either A[i] plus the previous MaxEndingHere, or just A[i], whichever is larger.
10+
11+
O(n)
12+
O(1)
13+
14+
*/
15+
16+
public class Solution
217
{
3-
public int maxSubArray(int[] nums)
18+
public int maxSubArray(int[] nums)
419
{
520
int max = nums[0], maxSoFar = nums[0];
621
for(int i=1; i < nums.length; i++)
722
{
823
maxSoFar = maxSoFar > 0 ? maxSoFar + nums[i] : nums[i];
9-
max = Math.max(maxSoFar, max);
24+
max = Math.max(maxSoFar, max);
1025
}
1126
return max;
1227
}

0 commit comments

Comments
 (0)