-
Notifications
You must be signed in to change notification settings - Fork 17
/
MaxSumSubarray1.java
54 lines (40 loc) · 1.17 KB
/
MaxSumSubarray1.java
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
class Solution{
// Ist Method
int maxSubarraySum(int arr[], int n) {
int curMax = 0, ans = Integer.MIN_VALUE;
for(int i=0; i<n; i++) {
curMax += arr[i];
if(ans < curMax) ans = curMax;
if(curMax < 0) curMax = 0;
}
return ans;
}
// To print subarray
int maxSubarraySum(int arr[], int n){
int curMax = 0, start = 0, end = 0, s = 0;
int ans = Integer.MIN_VALUE;
for(int i=0; i<n; i++) {
curMax += arr[i];
if(ans < curMax) {
ans = curMax;
start = s;
end = i;
}
if(curMax < 0) {
curMax = 0;
s = i + 1;
}
}
return ans;
}
// 2nd Method
int maxSubarraySum(int arr[], int n) {
int curMax = arr[0];
int ans = arr[0];
for(int i=1; i<n; i++) {
curMax = Math.max(arr[i], curMax + arr[i]);
ans = Math.max(ans, curMax);
}
return ans;
}
}