Workspace Fractional Knapsack
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Fractional Knapsack visualizer

Learn Fractional Knapsack with a step-by-step Greedy & Intervals visualizer, JavaScript source code and a worked example. Practice scheduling and resource allocation.

INTERACTIVE EXECUTION STUDIO
LEARN BY DOING

Predict. Execute. Understand.

Follow the source code, inspect live state changes, and predict the next operation before revealing it.

1 / 4Execution step
Reference example · JavaScript
Inspect reference input
{
  "items": [
    [
      60,
      10
    ],
    [
      100,
      20
    ],
    [
      120,
      30
    ]
  ],
  "capacity": 50
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
items,capacity
},s)=>{
items.sort((a,b)=>b[0]/b[1]-a[0]/a[1]);
let total=0;
for(let [v,w] of items){
let x=Math.min(capacity,w);
total+=v*x/w;
capacity-=x;
s("Take highest value per weight",{
Items:items,Taken:[x],Remaining:[capacity],Value:[total]
})
}
return total
};

Execution canvas

Active Changed
STEP 1

Take highest value per weight

Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.

Items3 rows
Taken1 items
Remaining1 items
Value1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Greedy & Intervals · Scheduling and resource allocation

Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.

Example input

{
  "items": [
    [
      60,
      10
    ],
    [
      100,
      20
    ],
    [
      120,
      30
    ]
  ],
  "capacity": 50
}

Execution steps

  1. Take highest value per weight

Computed output

240
JavaScript reference implementation
const solve = ({
  items,capacity
},s)=>{
  items.sort((a,b)=>b[0]/b[1]-a[0]/a[1]);
  let total=0;
  for(let [v,w] of items){
    let x=Math.min(capacity,w);
    total+=v*x/w;
    capacity-=x;
    s("Take highest value per weight",{
      Items:items,Taken:[x],Remaining:[capacity],Value:[total]
    })
  }
  return total
};

Continue learning

Practice related DSA questions in the same topic.