Fractional Knapsack

Intermediate Greedy Techniques DSA practice problem on Onlearn.

Difficulty: medium.

Topics: Fractional Knapsack Problem (Greedy Method), Greedy Algorithm, Sorting, Basic Arithmetic, Optimization, Time Complexity, Space Complexity, Object Sorting, greedy algorithm, iterative algorithms, sorting algorithms, time complexity analysis, Custom Sorting Criteria, Greedy Strategies.

Problem Statement Given a set of N items, each with a specific value and weight, and a knapsack with a maximum weight capacity W , your task is to determine the maximum total value that can be put into the knapsack. Unlike the 0/1 Knapsack problem, you are allowed to break items. This means if a whole item cannot fit into the remaining capacity, you can take a fraction of the item to fill the knapsack. The value of a fraction of an item is proportional to the amount of weight taken (e.g., half the weight of an item equals half its value). Input Specification The first line contains two integers N and W separated by a space, representing the number of items and the knapsack capacity respectively. The second line contains N space separated integers representing the values of the items. The third line contains N space separated integers representing the weights of the items. Output Specification A single number representing the maximum total value achievable. The output should be formatted to 2 decimal places (e.g., 240.00). Constraints 1 ≤ N ≤ 10^5 1 ≤ W ≤ 10^9 1 ≤ value, weight ≤ 10^5 Array lengths for values and weights will always be equal to N. Sample Test Cases Sample Input 1 Sample Output 1 Explanation: The items have the following value to weight ratios: 1. Item 1: 60/10 = 6.0 2. Item 2: 100/20 = 5.0 3. Item 3: 120/30 = 4.0 Strategy: Take Item 1 (Weight: 10, Value: 60). Remaining Capacity: 40. Take Item 2 (Weight: 20, Value: 100). Remaining Capacity: 20. Take 20/30 of Item 3 (Weight: 20, Value: 120 (2/3) = 80). Remaining Capacity: 0. Total Value = 60 + 100 + 80 = 240.00. Sample Input 2 Sample Output 2 Explanation: The total weight of all items (10 + 20 = 30) is less than the knapsack capacity (50). Therefore, we can pick all items completely. Total Value = 60 + 100 = 160.00. Difficulty Level Medium