forked from AllAlgorithms/cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimumProductSubset.cpp
More file actions
59 lines (46 loc) · 907 Bytes
/
Copy pathminimumProductSubset.cpp
File metadata and controls
59 lines (46 loc) · 907 Bytes
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
//Find minimum product subset in an array using Greedy method
#include <bits/stdc++.h>
using namespace std;
int calculate(int a[], int n)
{
if (n == 1)
return a[0];
int max_neg = INT_MIN;
int min_pos = INT_MAX;
int count_neg = 0, count_zero = 0;
int prod = 1;
for (int i = 0; i < n; i++) {
if (a[i] == 0) {
count_zero++;
continue;
}
if (a[i] < 0) {
count_neg++;
max_neg = max(max_neg, a[i]);
}
if (a[i] > 0)
min_pos = min(min_pos, a[i]);
prod = prod * a[i];
}
if (count_zero == n ||
(count_neg == 0 && count_zero > 0))
return 0;
if (count_neg == 0)
return min_pos;
if (!(count_neg & 1) && count_neg != 0) {
prod = prod / max_neg;
}
return prod;
}
int main()
{
int n;
cout<<"Enter size of array: ";
cin>>n;
int a[n];
cout<<"\nEnter array elements: ";
for(int i=0;i<n;i++)
cin>>a[i];
cout << "\nAnswer: "<<calculate(a, n);
return 0;
}