-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkadens.java
More file actions
52 lines (37 loc) · 1.12 KB
/
Copy pathkadens.java
File metadata and controls
52 lines (37 loc) · 1.12 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
public class kadens {
class Solution {
// arr: input array
// Function to find the sum of contiguous subarray with maximum sum.
long maxSubarraySum(int[] arr) {
int ms = Integer.MIN_VALUE;
int cs = 0;
boolean allNegative = true;
for(int i=0; i<arr.length; i++){
cs += arr[i];
if(cs < 0){
cs =0;
}
ms = Math.max(cs,ms);
if(arr[i] >= 0 ){
allNegative = false;
}
}
if(allNegative){
return -1;
}
return ms;
}
int maxSubarraySum2(int[] arr) {
if (arr.length == 0) {
return -1;
}
int maxCurrent = arr[0];
int maxGlobal = arr[0];
for (int i = 1; i < arr.length; i++) {
maxCurrent = Math.max(arr[i], maxCurrent + arr[i]);
maxGlobal = Math.max(maxGlobal, maxCurrent);
}
return maxGlobal;
}
}
}