Skip to content

Commit c9d2ef6

Browse files
authored
Merge pull request #301 from ameycodes/master
2 parents d1aa70f + e08684c commit c9d2ef6

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed

algorithms/greedy/minimumCoins.cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Given a value V and the list of available denomination of money,
2+
// find minimum number of coins and/or notes needed to make the change.
3+
4+
#include <bits/stdc++.h>
5+
using namespace std;
6+
7+
// All denominations of Indian Currency
8+
int deno[] = { 1, 2, 5, 10, 20,
9+
50, 100, 500, 1000 };
10+
int n = sizeof(deno) / sizeof(deno[0]);
11+
12+
vector<int> calculate(int V)
13+
{
14+
sort(deno, deno + n);
15+
vector<int> ans;
16+
17+
for (int i = n - 1; i >= 0; i--) {
18+
19+
while (V >= deno[i]) {
20+
V -= deno[i];
21+
ans.push_back(deno[i]);
22+
}
23+
}
24+
return ans;
25+
//for (int i = 0; i < ans.size(); i++)
26+
//cout << ans[i] << " ";
27+
}
28+
29+
int main()
30+
{
31+
int n;
32+
cout<<"Enter the monitory value: ";
33+
cin>>n;
34+
cout << "Following is minimal number of change for " << n
35+
<< ": ";
36+
vector<int> ans = calculate(n);
37+
for(auto i: ans)
38+
cout<<i<<" ";
39+
cout<<"\nMinimum Denominations required: "<<ans.size();
40+
return 0;
41+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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<<"\nEnter array elements: ";
55+
for(int i=0;i<n;i++)
56+
cin>>a[i];
57+
cout << "\nAnswer: "<<calculate(a, n);
58+
return 0;
59+
}

0 commit comments

Comments
 (0)