File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Find minimum product subset in an array using Greedy method
2
+
3
+ #include < bits/stdc++.h>
4
+ using namespace std ;
5
+
6
+ int calculate (int a[], int n)
7
+ {
8
+ if (n == 1 )
9
+ return a[0 ];
10
+
11
+ int max_neg = INT_MIN;
12
+ int min_pos = INT_MAX;
13
+ int count_neg = 0 , count_zero = 0 ;
14
+ int prod = 1 ;
15
+ for (int i = 0 ; i < n; i++) {
16
+
17
+
18
+ if (a[i] == 0 ) {
19
+ count_zero++;
20
+ continue ;
21
+ }
22
+
23
+ if (a[i] < 0 ) {
24
+ count_neg++;
25
+ max_neg = max (max_neg, a[i]);
26
+ }
27
+
28
+ if (a[i] > 0 )
29
+ min_pos = min (min_pos, a[i]);
30
+
31
+ prod = prod * a[i];
32
+ }
33
+
34
+ if (count_zero == n ||
35
+ (count_neg == 0 && count_zero > 0 ))
36
+ return 0 ;
37
+
38
+ if (count_neg == 0 )
39
+ return min_pos;
40
+
41
+ if (!(count_neg & 1 ) && count_neg != 0 ) {
42
+ prod = prod / max_neg;
43
+ }
44
+
45
+ return prod;
46
+ }
47
+
48
+ int main ()
49
+ {
50
+ int n;
51
+ cout<<" Enter size of array: " ;
52
+ cin>>n;
53
+ int a[n];
54
+ cout<<" \n Enter array elements: " ;
55
+ for (int i=0 ;i<n;i++)
56
+ cin>>a[i];
57
+ cout << " \n Answer: " <<calculate (a, n);
58
+ return 0 ;
59
+ }
You can’t perform that action at this time.
0 commit comments