Algorithm to increase the maximum product
Time limit: 1.0s Memory Limit: 512.0MB
Problem Description
For the number n, the number removed from m, how to take the product so that the maximum number m of it?
Input Format
The first line number data representing a number of sets
of input data each of 2 lines:
Line 1 shows the total number and the number n of the number m of the number to be taken, 1 <= n <= m <= 15,
this in turn gives the second row of n numbers, wherein each number range satisfying: a [i] is the absolute value of 4 or less.
Output Format
Each data output line 1, the largest product.
Sample input
1
5 5
1 2 3 4 2
Sample Output
48
#include <cstdio>
#include <climits>
#include <vector>
using namespace std;
int n, m;
int a[20];
int max_prod;
vector<int> chosen_idx;
void find_max_prod(int current_idx, int num_chosen)
{
if (num_chosen == m)
{
int prod = 1;
for (int i = 0; i < chosen_idx.size(); ++i)
prod *= a[chosen_idx[i]];
if (prod > max_prod)
max_prod = prod;
}
else if (current_idx >= n)
return;
else
{
chosen_idx.push_back(current_idx);
find_max_prod(current_idx + 1, num_chosen + 1);
chosen_idx.pop_back();
find_max_prod(current_idx + 1, num_chosen);
}
}
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
scanf("%d %d", &n, &m);
for (int i = 0; i < n; ++i)
scanf("%d", &a[i]);
max_prod = INT_MIN;
chosen_idx.clear();
find_max_prod(0, 0);
printf("%d\n", max_prod);
}
return 0;
}