-
Notifications
You must be signed in to change notification settings - Fork 207
/
Copy pathsum.java
48 lines (41 loc) · 1.2 KB
/
sum.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
import java.util.*;
import java.math.*;
public class sum {
static void printMaxSum(int[] arr){
//1) For max continuous sub array
int max_ending_here = 0;
int max_so_far = Integer.MIN_VALUE;
/*OR int max_so_far = arr[0];*/
for(int x : arr){
max_ending_here = Math.max(x, max_ending_here + x);
max_so_far = Math.max(max_so_far, max_ending_here);
}
System.out.print(max_so_far);
//2) For max non-continuous sub array, order doesn't matter
Arrays.sort(arr);
int sum = 0;
//if there is none positive value in entire array
if(arr[arr.length-1] <= 0)
sum = arr[arr.length - 1];
//accumulate all positive values in entire array
else{
for(int x : arr){
if(x > 0)
sum += x;
}
}
System.out.println(" " + sum);
}
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i=0; i<t ; i++) {
int n = sc.nextInt();
int [] arr = new int[n];
for(int j=0; j<n; j++) {
arr[j] = sc.nextInt();
}
printMaxSum(arr);
}
}
}