forked from Annex5061/java-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Java program to find maximum product of.java
78 lines (62 loc) · 1.54 KB
/
Java program to find maximum product of.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
// Java program to find maximum product of
// a subset.
class Array {
static int minProductSubset(int a[], int n)
{
if (n == 1)
return a[0];
// Find count of negative numbers,
// count of zeros, maximum valued
// negative number, minimum valued
// positive number and product of
// non-zero numbers
int negmax = Integer.MIN_VALUE;
int posmin = Integer.MAX_VALUE;
int count_neg = 0, count_zero = 0;
int product = 1;
for (int i = 0; i < n; i++) {
// if number is zero,count it
// but dont multiply
if (a[i] == 0) {
count_zero++;
continue;
}
// count the negative numbers
// and find the max negative number
if (a[i] < 0) {
count_neg++;
negmax = Math.max(negmax, a[i]);
}
// find the minimum positive number
if (a[i] > 0 && a[i] < posmin)
posmin = a[i];
product *= a[i];
}
// if there are all zeroes
// or zero is present but no
// negative number is present
if (count_zero == n
|| (count_neg == 0 && count_zero > 0))
return 0;
// If there are all positive
if (count_neg == 0)
return posmin;
// If there are even number except
// zero of negative numbers
if (count_neg % 2 == 0 && count_neg != 0) {
// Otherwise result is product of
// all non-zeros divided by maximum
// valued negative.
product = product / negmax;
}
return product;
}
// main function
public static void main(String[] args)
{
int a[] = { -1, -1, -2, 4, 3 };
int n = 5;
System.out.println(minProductSubset(a, n));
}
}
// This code is contributed by Arnab Kundu.