Skip to content

Commit e4e9111

Browse files
add implementation of minimum product subset calculation
1 parent 1653d78 commit e4e9111

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

31Greedy/01_min_prod_subset.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
int minProduct(vector<int>& v){
5+
int cnt_negative = 0, cnt_zero = 0, cnt_pos = 0;
6+
int prod_pos = 1, prod_neg = 1;
7+
int largest_neg = INT_MIN;
8+
for(const int ele: v){
9+
if(ele<0) {
10+
cnt_negative++;
11+
prod_neg *= ele;
12+
largest_neg = max(largest_neg, ele);
13+
}
14+
if(ele==0) cnt_zero++;
15+
if(ele>0) {
16+
cnt_pos++;
17+
prod_pos *= ele;
18+
}
19+
}
20+
//no negative exists
21+
if(cnt_negative==0){
22+
if(cnt_zero>0) return 0;
23+
else {
24+
auto it = min_element(v.begin(), v.end());
25+
return *(it);
26+
}
27+
}else{//negatives exist
28+
if(cnt_negative%2 == 0){//return products of all -ve except largest one
29+
return (prod_neg / largest_neg) * prod_pos;
30+
}else{
31+
//product of all +ve and -ve
32+
return prod_neg*prod_pos;
33+
}
34+
}
35+
}
36+
37+
int main(){
38+
vector<int> v {2, 3, 1, 4, 2, 0};
39+
cout<<minProduct(v);
40+
}

31Greedy/01_min_prod_subset.exe

150 KB
Binary file not shown.

0 commit comments

Comments
 (0)