Sum and product of K smallest and largest Fibonacci numbers in the array
Given an integer K and an array arr[] containing N integers, the task is to find the sum and product of K smallest and K largest fibonacci numbers in the array. Note: Assume that there are at least K fibonacci numbers in the array. Examples:
Input: arr[] = {2, 5, 6, 8, 10, 11}, K = 2 Output: Sum of K-minimum fibonacci numbers is 7 Product of K-minimum fibonacci numbers is 10 Sum of K-maximum fibonacci numbers is 13 Product of K-maximum fibonacci numbers is 40 Explanation : {2, 5, 8} are the only fibonacci numbers from the array. {2, 5} are the 2 smallest and {5, 8} are the 2 largest among them. Input: arr[] = {3, 2, 12, 13, 5, 19}, K = 3 Output: Sum of K-minimum fibonacci numbers is 10 Product of K-minimum fibonacci numbers is 30 Sum of K-maximum fibonacci numbers is 21 Product of K-maximum fibonacci numbers is 195
Approach: The idea is to use hashing to precompute and store the Fibonacci nodes up to the maximum value, in a Set, to make checking easy and efficient (in O(1) time).
- Traverse through the entire array and obtain the maximum value in the list.
- Now, build a hash table containing all the Fibonacci nodes less than or equal to the maximum value of the array.
After performing the above precomputation, traverse the array and insert all the numbers which are fibonacci in two heaps, a min heap and a max heap. Now, pop out top K elements from the min heap and max heap to compute the sum and product of the K Fibonacci numbers. Below is the implementation of the above approach:
CPP
// C++ program to find the sum and // product of K smallest and K // largest Fibonacci numbers in an array #include <bits/stdc++.h> using namespace std; // Function to create the hash table // to check Fibonacci numbers void createHash(set< int >& hash, int maxElement) { // Inserting the first two elements // into the hash int prev = 0, curr = 1; hash.insert(prev); hash.insert(curr); // Computing the remaining // elements using // the previous two elements while (curr <= maxElement) { int temp = curr + prev; hash.insert(temp); prev = curr; curr = temp; } } // Function that calculates the sum // and the product of K smallest and // K largest Fibonacci numbers in an array void fibSumAndProduct( int arr[], int n, int k) { // Find the maximum value in the array int max_val = *max_element(arr, arr + n); // Creating a hash containing // all the Fibonacci numbers // upto the maximum data value // in the array set< int > hash; createHash(hash, max_val); // Max Heap to store all the // Fibonacci numbers priority_queue< int > maxHeap; // Min Heap to store all the // Fibonacci numbers priority_queue< int , vector< int >, greater< int > > minHeap; // Push all the fibonacci numbers // from the array to the heaps for ( int i = 0; i < n; i++) if (hash.find(arr[i]) != hash.end()) { minHeap.push(arr[i]); maxHeap.push(arr[i]); } long long int minProduct = 1, maxProduct = 1, minSum = 0, maxSum = 0; // Finding the K minimum // and the K maximum // elements from the heaps while (k--) { // Calculate the products minProduct *= minHeap.top(); maxProduct *= maxHeap.top(); // Calculate the sum minSum += minHeap.top(); maxSum += maxHeap.top(); // Pop the current // minimum element minHeap.pop(); // Pop the current // maximum element maxHeap.pop(); } cout << "Sum of K-minimum " << "fibonacci numbers is " << minSum << "\n" ; cout << "Product of K-minimum " << "fibonacci numbers is " << minProduct << "\n" ; cout << "Sum of K-maximum " << "fibonacci numbers is " << maxSum << "\n" ; cout << "Product of K-maximum " << "fibonacci numbers is " << maxProduct; } // Driver code int main() { int arr[] = { 2, 5, 6, 8, 10, 11 }; int N = sizeof (arr) / sizeof (arr[0]); int K = 2; fibSumAndProduct(arr, N, K); return 0; } |
Java
import java.util.*; public class FibonacciSumProduct { // Function to create the hash table // to check Fibonacci numbers public static void createHash(HashSet<Integer> hash, int maxElement) { // Inserting the first two elements // into the hash int prev = 0 , curr = 1 ; hash.add(prev); hash.add(curr); // Computing the remaining // elements using // the previous two elements while (curr <= maxElement) { int temp = curr + prev; hash.add(temp); prev = curr; curr = temp; } } // Function that calculates the sum // and the product of K smallest and // K largest Fibonacci numbers in an array public static void fibSumAndProduct( int [] arr, int n, int k) { // Find the maximum value in the array int max_val = Arrays.stream(arr).max().getAsInt(); // Creating a hash containing // all the Fibonacci numbers // upto the maximum data value // in the array HashSet<Integer> hash = new HashSet<>(); createHash(hash, max_val); // Max Heap to store all the // Fibonacci numbers PriorityQueue<Integer> maxHeap = new PriorityQueue<>( Collections.reverseOrder()); // Min Heap to store all the // Fibonacci numbers PriorityQueue<Integer> minHeap = new PriorityQueue<>(); // Push all the fibonacci numbers // from the array to the heaps for ( int i = 0 ; i < n; i++) if (hash.contains(arr[i])) { minHeap.add(arr[i]); maxHeap.add(arr[i]); } long minProduct = 1L, maxProduct = 1L, minSum = 0L, maxSum = 0L; // Finding the K minimum // and the K maximum // elements from the heaps while (k-- > 0 ) { // Calculate the products minProduct *= minHeap.peek(); maxProduct *= maxHeap.peek(); // Calculate the sum minSum += minHeap.peek(); maxSum += maxHeap.peek(); // Pop the current // minimum element minHeap.poll(); // Pop the current // maximum element maxHeap.poll(); } System.out.println( "Sum of K-minimum " + "fibonacci numbers is " + minSum); System.out.println( "Product of K-minimum " + "fibonacci numbers is " + minProduct); System.out.println( "Sum of K-maximum " + "fibonacci numbers is " + maxSum); System.out.println( "Product of K-maximum " + "fibonacci numbers is " + maxProduct); } // Driver code public static void main(String[] args) { int [] arr = { 2 , 5 , 6 , 8 , 10 , 11 }; int n = arr.length; int k = 2 ; fibSumAndProduct(arr, n, k); } } |
Python3
# Python3 program to find the sum and # product of K smallest and K # largest Fibonacci numbers in an array import heapq # Function to create the hash table # to check Fibonacci numbers def createHash( hash , maxElement): # Inserting the first two elements # into the hash prev, curr = 0 , 1 hash .add(prev) hash .add(curr) # Computing the remaining # elements using # the previous two elements while curr < = maxElement: temp = curr + prev hash .add(temp) prev = curr curr = temp # Function that calculates the sum # and the product of K smallest and # K largest Fibonacci numbers in an array def fibSumAndProduct(arr, n, k): # Find the maximum value in the array max_val = max (arr) # Creating a hash containing # all the Fibonacci numbers # upto the maximum data value # in the array hash = set () createHash( hash , max_val) # Min Heap to store all the # Fibonacci numbers minHeap = [] # Max Heap to store all the # Fibonacci numbers maxHeap = [] # Push all the fibonacci numbers # from the array to the heaps for i in range (n): if arr[i] in hash : heapq.heappush(minHeap, arr[i]) heapq.heappush(maxHeap, - arr[i]) minProduct, maxProduct, minSum, maxSum = 1 , 1 , 0 , 0 # Finding the K minimum # and the K maximum # elements from the heaps while k > 0 : # Pop the current # minimum element min_num = heapq.heappop(minHeap) # Pop the current # maximum element max_num = - heapq.heappop(maxHeap) # Calculate the products minProduct * = min_num maxProduct * = max_num # Calculate the sum minSum + = min_num maxSum + = max_num k - = 1 print ( "Sum of K-minimum fibonacci numbers is" , minSum) print ( "Product of K-minimum fibonacci numbers is" , minProduct) print ( "Sum of K-maximum fibonacci numbers is" , maxSum) print ( "Product of K-maximum fibonacci numbers is" , maxProduct) # Driver code if __name__ = = '__main__' : arr = [ 2 , 5 , 6 , 8 , 10 , 11 ] N = len (arr) K = 2 fibSumAndProduct(arr, N, K) |
Javascript
// Javascript program to find the sum and // product of K smallest and K // largest Fibonacci numbers in an array // Function to create the hash table // to check Fibonacci numbers function createHash(hash, maxElement) { // Inserting the first two elements // into the hash let prev = 0, curr = 1; hash.add(prev); hash.add(curr); // Computing the remaining // elements using // the previous two elements while (curr <= maxElement) { let temp = curr + prev; hash.add(temp); prev = curr; curr = temp; } } // Function that calculates the sum // and the product of K smallest and // K largest Fibonacci numbers in an array function fibSumAndProduct(arr, n, k) { // Find the maximum value in the array let max_val = arr.reduce((a, b) => Math.max(a, b), -Infinity); // Creating a hash containing // all the Fibonacci numbers // upto the maximum data value // in the array let hash = new Set(); createHash(hash, max_val); // Max Heap to store all the // Fibonacci numbers let maxHeap = []; // Min Heap to store all the // Fibonacci numbers let minHeap = []; // Push all the fibonacci numbers // from the array to the heaps for (let i = 0; i < n; i++) if (hash.has(arr[i])) { minHeap.push(arr[i]); minHeap.sort((a, b)=>(a-b)); maxHeap.push(arr[i]); maxHeap.sort((a, b)=>(b-a)); } let minProduct = 1; let maxProduct = 1; let minSum = 0; let maxSum = 0; // Finding the K minimum // and the K maximum // elements from the heaps while (k--) { // Calculate the products minProduct *= minHeap[0]; maxProduct *= maxHeap[0]; // Calculate the sum minSum += minHeap[0]; maxSum += maxHeap[0]; // Pop the current // minimum element minHeap.shift(); // Pop the current // maximum element maxHeap.shift(); } console.log( "Sum of K-minimum fibonacci numbers is " , minSum); console.log( "Product of K-minimum fibonacci numbers is " , minProduct); console.log( "Sum of K-maximum fibonacci numbers is " , maxSum); console.log( "Product of K-maximum fibonacci numbers is " , maxProduct); } // Driver code let arr = [2, 5, 6, 8, 10, 11]; let N = arr.length; let K = 2; fibSumAndProduct(arr, N, K); // The code is contributed by Nidhi goel. |
C#
// C# program to find the sum and // product of K smallest and K // largest Fibonacci numbers in an array using System; using System.Collections.Generic; using System.Linq; class Program { // Function to create the hash table // to check Fibonacci numbers static void CreateHash(HashSet< int > hash, int maxElement) { // Inserting the first two elements // into the hash int prev = 0, curr = 1; hash.Add(prev); hash.Add(curr); // Computing the remaining // elements using // the previous two elements while (curr <= maxElement) { int temp = curr + prev; hash.Add(temp); prev = curr; curr = temp; } } // Function that calculates the sum // and the product of K smallest and // K largest Fibonacci numbers in an array static void FibSumAndProduct( int [] arr, int n, int k) { int max_val = arr.Max(); // Creating a hash containing // all the Fibonacci numbers // upto the maximum data value // in the array HashSet< int > hash = new HashSet< int >(); CreateHash(hash, max_val); // Max Heap to store all the // Fibonacci numbers List< int > maxHeap = new List< int >(); // Min Heap to store all the // Fibonacci numbers List< int > minHeap = new List< int >(); // Push all the fibonacci numbers // from the array to the heaps for ( int i = 0; i < n; i++) { if (hash.Contains(arr[i])) { minHeap.Add(arr[i]); minHeap.Sort(); maxHeap.Add(arr[i]); maxHeap.Sort(); maxHeap.Reverse(); } } int minProduct = 1; int maxProduct = 1; int minSum = 0; int maxSum = 0; // Finding the K minimum // and the K maximum // elements from the heaps for ( int i = 0; i < k; i++) { minProduct *= minHeap[i]; maxProduct *= maxHeap[i]; // Pop the current // minimum element minSum += minHeap[i]; // Pop the current // maximum element maxSum += maxHeap[i]; } Console.WriteLine( "Sum of K-minimum fibonacci numbers is {0}" , minSum); Console.WriteLine( "Product of K-minimum fibonacci numbers is {0}" , minProduct); Console.WriteLine( "Sum of K-maximum fibonacci numbers is {0}" , maxSum); Console.WriteLine( "Product of K-maximum fibonacci numbers is {0}" , maxProduct); } // Driver code static void Main( string [] args) { int [] arr = { 2, 5, 6, 8, 10, 11 }; int N = arr.Length; int K = 2; FibSumAndProduct(arr, N, K); } } |
Sum of K-minimum fibonacci numbers is 7 Product of K-minimum fibonacci numbers is 10 Sum of K-maximum fibonacci numbers is 13 Product of K-maximum fibonacci numbers is 40
Time Complexity : O(K log N)
Space Complexity : O(N)
Contact Us