Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitc5c643a

Browse files
authored
Create SubSequence With Maximum Odd Sum
1 parent65a3f5b commitc5c643a

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

‎SubSequence With Maximum Odd Sum‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package hackerRank.problem.practice;
2+
3+
import java.io.BufferedReader; // Time Complexity:O(n)
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.io.PrintWriter;
7+
8+
public class Stats1{
9+
public static void main(String[] args) throws IOException {
10+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
11+
PrintWriter wr = new PrintWriter(System.out);
12+
int T = Integer.parseInt(br.readLine().trim());
13+
for(int t_i=0; t_i<T; t_i++)
14+
{
15+
int N = Integer.parseInt(br.readLine().trim());
16+
String[] arr = br.readLine().split(" ");
17+
int[] array_int = new int[N];
18+
for(int i=0; i<arr.length; i++)
19+
{
20+
array_int[i] = Integer.parseInt(arr[i]);
21+
}
22+
23+
int out_ = findMaxOddSubarraySum(array_int,N);
24+
System.out.println(out_);
25+
}
26+
27+
wr.close();
28+
br.close();
29+
}
30+
static int findMaxOddSubarraySum(int arr[], int n)
31+
{
32+
// Here min_odd is the minimum odd number (in
33+
// absolute terms). Initializing with max value
34+
// of int .
35+
int m = Integer.MAX_VALUE;
36+
37+
// To check if there is al-least one odd number.
38+
boolean isOdd = false;
39+
40+
int sum = 0; // To store sum of all positive elements
41+
for (int i=0 ; i<n ; i++)
42+
{
43+
// Adding positive number would increase
44+
// the sum.
45+
if (arr[i] > 0)
46+
sum = sum + arr[i];
47+
48+
// To find the minimum odd number(absolute)
49+
// in the array.
50+
if (arr[i]%2 != 0)
51+
{
52+
isOdd = true;
53+
if (m > Math.abs(arr[i]))
54+
m = Math.abs(arr[i]);
55+
}
56+
}
57+
58+
// If there was no odd number
59+
if (isOdd == false)
60+
return -1;
61+
62+
// Now, sum will be either odd or even.
63+
// If even, changing it to odd. As, even - odd = odd.
64+
// since m is the minimum odd number(absolute).
65+
if (sum%2 == 0)
66+
sum = sum - m;
67+
68+
return sum;
69+
}
70+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp