VOOZH about

URL: https://www.geeksforgeeks.org/dsa/fractional-knapsack-queries/

⇱ Fractional Knapsack Queries - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Fractional Knapsack Queries

Last Updated : 11 Jul, 2025

Given an integer array, consisting of positive weights "W" and their values "V" respectively as a pair and some queries consisting of an integer 'C' specifying the capacity of the knapsack, find the maximum value of products that can be put in the knapsack if the breaking of items is allowed. Examples:

Input: arr[] = { {1, 2}, {1, 3}, {3, 7} }, q = {1, 2, 3, 4, 5} Output: {3, 5.33333, 7.66667, 10, 12} For 'C' = 1, we will fill the knap-sack with element of value 3. For 'C' = 2, first, we fill with element of value 3, then remaining 1 capacity with element with value 7. For 'C' = 3, first we fill with element of value 3, then remaining 2 capacities with element with value 7. For 'C' = 4, first we fill with element of value 3, then remaining 3 capacities with element with value 7. For 'C' = 5, first we fill with element of value 3, next 3 capacities with element with value 7 and remaining 1 with element of value 1.

Its recommended you go through this article on Fractional knapsack before going through this article. Naive Approach: A simple approach will be to sort the array in decreasing order of V/W values i.e. there value/weight ratio. Then, for each query, we will iterate the array sum up the required integer values while the knap-sack isn't completely full. Time Complexity : O(q*n*log(n)) Efficient approach: Queries can be optimized by performing prefix_sum of a sorted array on both weight and value. Below is the algorithm:

  1. Sort the array by their Value/Weight ratio in descending order.
  2. Find prefix-sum of Weight and Value respectively of the array.
  3.  
    • Perform a binary search to find the first element with prefix_sum on weight(W) larger than 'C'. Strictly speaking, find upper bound on the value of 'C' in a prefix_sum array of 'W'. Let's say this element is at an index 'X'.
    • Include sum of values from index {0, X-1} and the fractional value from index 'X' that can be accommodated in remaining capacity.

Below is the implementation of the above approach: 

Time Complexity : O((n+q)*log(n))

Comment
Article Tags: