-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathMaxSumContinuousSubarray.java
More file actions
75 lines (41 loc) · 1.08 KB
/
MaxSumContinuousSubarray.java
File metadata and controls
75 lines (41 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
Max Sum Contiguous Subarray
Problem Description
Find the contiguous subarray within an array, A of length N which has the largest sum.
Problem Constraints
1 <= N <= 1e6
-1000 <= A[i] <= 1000
Input Format
The first and the only argument contains an integer array, A.
Output Format
Return an integer representing the maximum possible sum of the contiguous subarray.
Example Input
Input 1:
A = [1, 2, 3, 4, -10]
Input 2:
A = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Example Output
Output 1:
10
Output 2:
6
Example Explanation
Explanation 1:
The subarray [1, 2, 3, 4] has the maximum possible sum of 10.
Explanation 2:
The subarray [4,-1,2,1] has the maximum possible sum of 6.
*/
public class Solution {
// DO NOT MODIFY THE ARGUMENTS WITH "final" PREFIX. IT IS READ ONLY
public int maxSubArray(final int[] A) {
int max = Integer.MIN_VALUE;
int sum = 0;
for(int i=0;i<A.length;i++){
sum += A[i];
max = Integer.max(sum, max);
if(sum<0)
sum = 0;
}
return max;
}
}