-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubSequence With Maximum Odd Sum
70 lines (60 loc) · 2 KB
/
SubSequence With Maximum Odd Sum
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
package hackerRank.problem.practice;
import java.io.BufferedReader; // Time Complexity:O(n)
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class Stats1{
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter wr = new PrintWriter(System.out);
int T = Integer.parseInt(br.readLine().trim());
for(int t_i=0; t_i<T; t_i++)
{
int N = Integer.parseInt(br.readLine().trim());
String[] arr = br.readLine().split(" ");
int[] array_int = new int[N];
for(int i=0; i<arr.length; i++)
{
array_int[i] = Integer.parseInt(arr[i]);
}
int out_ = findMaxOddSubarraySum(array_int,N);
System.out.println(out_);
}
wr.close();
br.close();
}
static int findMaxOddSubarraySum(int arr[], int n)
{
// Here min_odd is the minimum odd number (in
// absolute terms). Initializing with max value
// of int .
int m = Integer.MAX_VALUE;
// To check if there is al-least one odd number.
boolean isOdd = false;
int sum = 0; // To store sum of all positive elements
for (int i=0 ; i<n ; i++)
{
// Adding positive number would increase
// the sum.
if (arr[i] > 0)
sum = sum + arr[i];
// To find the minimum odd number(absolute)
// in the array.
if (arr[i]%2 != 0)
{
isOdd = true;
if (m > Math.abs(arr[i]))
m = Math.abs(arr[i]);
}
}
// If there was no odd number
if (isOdd == false)
return -1;
// Now, sum will be either odd or even.
// If even, changing it to odd. As, even - odd = odd.
// since m is the minimum odd number(absolute).
if (sum%2 == 0)
sum = sum - m;
return sum;
}
}