Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f229dd6

Browse files
Create Max Sum Contiguous Subarray .java
1 parent a9866bd commit f229dd6

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

‎Array/Max Sum Contiguous Subarray .java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
Find the contiguous subarray within an array, A of length N which has the largest sum.
3+
4+
Input Format:
5+
6+
The first and the only argument contains an integer array, A.
7+
Output Format:
8+
9+
Return an integer representing the maximum possible sum of the contiguous subarray.
10+
Constraints:
11+
12+
1 <= N <= 1e6
13+
-1000 <= A[i] <= 1000
14+
For example:
15+
16+
Input 1:
17+
A = [1, 2, 3, 4, -10]
18+
19+
Output 1:
20+
10
21+
22+
Explanation 1:
23+
The subarray [1, 2, 3, 4] has the maximum possible sum of 10.
24+
25+
Input 2:
26+
A = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
27+
28+
Output 2:
29+
6
30+
31+
Explanation 2:
32+
The subarray [4,-1,2,1] has the maximum possible sum of 6.
33+
*/
34+
35+
36+
public class Solution {
37+
// DO NOT MODIFY THE LIST. IT IS READ ONLY
38+
public int maxSubArray(final List<Integer> A) {
39+
int len = A.size();
40+
if(len == 0)
41+
return 0;
42+
int sum = 0;
43+
int maxSum = Integer.MIN_VALUE;
44+
for(int i = 0; i<len; i++)
45+
{
46+
sum = Math.max(sum+A.get(i), A.get(i) );
47+
maxSum = Math.max(maxSum , sum);
48+
}
49+
return maxSum;
50+
}
51+
}
52+
53+
54+
55+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /