-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxsubarraytoprefix.java
More file actions
43 lines (28 loc) · 1023 Bytes
/
Copy pathMaxsubarraytoprefix.java
File metadata and controls
43 lines (28 loc) · 1023 Bytes
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
import java.util.*;
public class Maxsubarraytoprefix{
public static void prefix(int numbers[]){
int currentSum = 0;
int MaxSum = Integer.MIN_VALUE;
int prefix[] = new int[numbers.length];
prefix[0] = numbers[0];
for(int i=1; i<prefix.length; i++){
prefix[i] = prefix[i-1] + numbers[i];
}
for(int i = 0; i<numbers.length; i++){
int start = i;
for(int j=i; j<numbers.length; j++){
int end = j;
currentSum = start == 0 ? prefix[end] : prefix[end] - prefix[start-1];
System.out.println(currentSum);
if(MaxSum < currentSum) {
MaxSum = currentSum;
}
}
}
System.out.println("max sum = " + MaxSum);
}
public static void main(String []args){
int numbers[] = {1, -2, 6, -1, 3};
prefix(numbers);
}
}