Given an array arr[] containing n positive integers and an integer k. Your task is to find the minimum possible product of k elements of the given array.
Examples:
Input: arr[] = [198, 76, 544, 123, 154, 675], k = 2
Output: 9348
Explanation: We will choose two smallest numbers from the given array to get the minimum product. The two smallest numbers are 76 and 123, and their product is 9348.Input: arr[] = [5, 4, 1, 2, 3], k = 3
Output: 6
Explanation: We will choose three smallest numbers from the given array to get the minimum product. The three smallest numbers are 1, 2, and 3, and their product is 6.
[Naive Approach] - Using Sorting - O(n * log n) Time and O(1) Space
To get the minimum product of k elements, we are required to choose the k smallest elements. We sort the given array in ascending order, and find the product of first k elements of the sorted array.
#include <bits/stdc++.h>
using namespace std;
int minProduct(vector<int> &arr, int k) {
// sort the array
sort(arr.begin(), arr.end());
// to store the result
int res = 1;
// find product of first k elements
for(int i = 0; i < k; i++) {
res *= arr[i];
}
return res;
}
int main() {
vector<int> arr = { 198, 76, 544, 123, 154, 675 };
int k = 2;
cout << minProduct(arr, k);
return 0;
}
import java.util.Arrays;
public class Main {
public static int minProduct(int[] arr, int n, int k)
{
Arrays.sort(arr);
long result = 1;
for (int i = 0; i < k; i++) {
result = (arr[i] * result);
}
return (int)result;
}
public static void main(String[] args)
{
int[] arr = { 198, 76, 544, 123, 154, 675 };
int k = 2;
int n = arr.length;
System.out.println("Minimum product is "
+ minProduct(arr, n, k));
}
}
// This code is contributed by adityamaharshi21.
# Python program to find minimum product of
# k elements in an array
def minProduct(arr, n, k):
arr.sort()
result = 1
for i in range(k):
result = (arr[i] * result)
return result
# Driver code
arr = [198, 76, 544, 123, 154, 675]
k = 2
n = len(arr)
print("Minimum product is", minProduct(arr, n, k))
# This code is contributed by aadityamaharshi21.
// C# program to find minimum product of
// k elements in an array
using System;
using System.Collections.Generic;
public class GFG
{
public static long minProduct(int[] arr, int n, int k)
{
Array.Sort(arr);
long result = 1;
for(int i = 0; i<k; i++){
result = ((long)arr[i] * result);
}
return result;
}
// Driver Code
public static void Main(String[] args)
{
int []arr = {198, 76, 544, 123, 154, 675};
int k = 2;
int n = arr.Length;
Console.Write("Minimum product is " + minProduct(arr, n, k));
}
}
// This code is contributed by Yash Agarwal(yashagarwal2852002)
// JavaScript program to find minimum product of
// k elements in an array
function minProduct(arr, n, k) {
arr.sort((a, b) => a - b);
let result = 1;
for (let i = 0; i < k; i++) {
result = (arr[i] * result);
}
return result;
}
// Driver code
let arr = [198, 76, 544, 123, 154, 675];
let k = 2;
let n = arr.length;
console.log(`Minimum product is ${minProduct(arr, n, k)}`);
// This code is contributed by adityamaharshi21.
Output
9348
[Expected Approach] - Using Max Heap - O(n * log k) Time and O(k) Space
The idea is to use max heap (priority queue) to find the k smallest elements of the given array.
1) Create a max heap and push first k array elements into it.
2) For remaining n-k elements, compare each element with the heap top, if smaller, then remove root of the heap and insert into the heap. If greater than ignore.
3) Finally compute product of the heap elements.
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int minProduct(vector<int>& arr, int k) {
// Step 1: Create a max heap with first k elements
priority_queue<int> maxHeap;
for (int i = 0; i < k; ++i) {
maxHeap.push(arr[i]);
}
// Step 2: Process remaining elements
for (int i = k; i < arr.size(); ++i) {
if (arr[i] < maxHeap.top()) {
maxHeap.pop();
maxHeap.push(arr[i]);
}
}
// Step 3: Multiply elements in heap
int product = 1;
while (!maxHeap.empty()) {
product *= maxHeap.top();
maxHeap.pop();
}
return product;
}
int main() {
vector<int> arr1 = {198, 76, 544, 123, 154, 675};
cout << minProduct(arr1, 2) << endl; // Output: 9348
vector<int> arr2 = {5, 4, 1, 2, 3};
cout << minProduct(arr2, 3) << endl; // Output: 6
return 0;
}
import java.util.PriorityQueue;
import java.util.Arrays;
public class Main {
public static int minProduct(int[] arr, int k) {
// Step 1: Create a max heap with first k elements
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
for (int i = 0; i < k; ++i) {
maxHeap.add(arr[i]);
}
// Step 2: Process remaining elements
for (int i = k; i < arr.length; ++i) {
if (arr[i] < maxHeap.peek()) {
maxHeap.poll();
maxHeap.add(arr[i]);
}
}
// Step 3: Multiply elements in heap
int product = 1;
while (!maxHeap.isEmpty()) {
product *= maxHeap.poll();
}
return product;
}
public static void main(String[] args) {
int[] arr1 = {198, 76, 544, 123, 154, 675};
System.out.println(minProduct(arr1, 2)); // Output: 9348
int[] arr2 = {5, 4, 1, 2, 3};
System.out.println(minProduct(arr2, 3)); // Output: 6
}
}
import heapq
def min_product(arr, k):
# Step 1: Create a max heap with first k elements
max_heap = [-x for x in arr[:k]]
heapq.heapify(max_heap)
# Step 2: Process remaining elements
for i in arr[k:]:
if -i > max_heap[0]:
heapq.heappop(max_heap)
heapq.heappush(max_heap, -i)
# Step 3: Multiply elements in heap
product = 1
while max_heap:
product *= -heapq.heappop(max_heap)
return product
arr1 = [198, 76, 544, 123, 154, 675]
print(min_product(arr1, 2)) # Output: 9348
arr2 = [5, 4, 1, 2, 3]
print(min_product(arr2, 3)) # Output: 6
using System;
using System.Collections.Generic;
class Program {
public static int MinProduct(int[] arr, int k) {
// Step 1: Create a max heap with first k elements
SortedSet<int> maxHeap = new SortedSet<int>(Comparer<int>.Create((a, b) => b.CompareTo(a)));
for (int i = 0; i < k; ++i) {
maxHeap.Add(arr[i]);
}
// Step 2: Process remaining elements
for (int i = k; i < arr.Length; ++i) {
if (arr[i] < maxHeap.Max) {
maxHeap.Remove(maxHeap.Max);
maxHeap.Add(arr[i]);
}
}
// Step 3: Multiply elements in heap
int product = 1;
foreach (var num in maxHeap) {
product *= num;
}
return product;
}
static void Main() {
int[] arr1 = {198, 76, 544, 123, 154, 675};
Console.WriteLine(MinProduct(arr1, 2)); // Output: 9348
int[] arr2 = {5, 4, 1, 2, 3};
Console.WriteLine(MinProduct(arr2, 3)); // Output: 6
}
}
function minProduct(arr, k) {
// Step 1: Create a max heap with first k elements
const maxHeap = [];
for (let i = 0; i < k; ++i) {
maxHeap.push(arr[i]);
}
maxHeap.sort((a, b) => b - a);
// Step 2: Process remaining elements
for (let i = k; i < arr.length; ++i) {
if (arr[i] < maxHeap[0]) {
maxHeap.shift();
maxHeap.push(arr[i]);
maxHeap.sort((a, b) => b - a);
}
}
// Step 3: Multiply elements in heap
let product = 1;
for (const num of maxHeap) {
product *= num;
}
return product;
}
const arr1 = [198, 76, 544, 123, 154, 675];
console.log(minProduct(arr1, 2)); // Output: 9348
const arr2 = [5, 4, 1, 2, 3];
console.log(minProduct(arr2, 3)); // Output: 6
Output
9348