Skip to content

Commit 07483c5

Browse files
committed
Maximum Subarray
1 parent 713e585 commit 07483c5

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
eclipse.preferences.version=1
2+
encoding/<project>=UTF-8
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
eclipse.preferences.version=1
2+
org.eclipse.ltk.core.refactoring.enable.project.refactoring.history=false

MaximumSubarray.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Find the contiguous subarray within an array (containing at least one number)
3+
* which has the largest sum.
4+
*
5+
* For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray
6+
* [4,−1,2,1] has the largest sum = 6.
7+
*
8+
* click to show more practice.
9+
*
10+
* More practice: If you have figured out the O(n) solution, try coding another
11+
* solution using the divide and conquer approach, which is more subtle.
12+
*/
13+
14+
public class MaximumSubarray {
15+
public int maxSubArray(int[] A) {
16+
int max = Integer.MIN_VALUE;
17+
int sum = 0;
18+
for (int i = 0; i < A.length; i++) {
19+
sum += A[i];
20+
if (sum > max) {
21+
max = sum;
22+
}
23+
if (sum < 0) {
24+
sum = 0;
25+
}
26+
}
27+
return max;
28+
}
29+
}

0 commit comments

Comments
 (0)