-
Notifications
You must be signed in to change notification settings - Fork 0
/
Answer2.java
85 lines (74 loc) · 2.46 KB
/
Answer2.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package tcs;
import java.util.ArrayList;
import java.util.Scanner;
public class Answer2 {
static int maxAlternateSum(int arr[], int n)
{
// return maximum sum alternate sub-sequence
ArrayList<Integer> fairSequence = new ArrayList<>();
if(arr[0] < 0){
fairSequence.add(arr[0]);
int i=0;
while(i != arr.length-1){
int j=i+1;
int nextMaxPositive = Integer.MIN_VALUE;
for(j=i+1;j<n;j++){
if(arr[j] < 0){
break;
}
nextMaxPositive = Math.max(nextMaxPositive,arr[j]);
}
fairSequence.add(nextMaxPositive);
int k = j;
int nextMaxNegative = Integer.MIN_VALUE;
for( k= j;k<n;k++){
if(arr[k] > 0){
break;
}
nextMaxNegative = Math.max(nextMaxNegative,arr[k]);
}
fairSequence.add(nextMaxNegative);
i = k-1;
}
fairSequence.remove(fairSequence.size()-1);
}
if(arr[0] > 0){
int i=0;
while(i != arr.length-1){
int j=i+1;
int nextMaxNegative = Integer.MIN_VALUE;
for( j= i;j<n;j++) {
if (arr[j] < 0) {
break;
}
nextMaxNegative = Math.max(nextMaxNegative, arr[j]);
}
fairSequence.add(nextMaxNegative);
int k = j;
int nextMaxPositive = Integer.MIN_VALUE;
for(k=j;k<n;k++){
if(arr[k] > 0 && k < n-1){
break;
}
nextMaxPositive = Math.max(nextMaxPositive,arr[k]);
}
fairSequence.add(nextMaxPositive);
i = k-1;
}
}
int sum =0;
for (int e:fairSequence) {
sum+=e;
}
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n =sc.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
}
System.out.println(maxAlternateSum(arr,n));
}
}