Workspace Maximum Sum Combinations
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Maximum Sum Combinations visualizer

Learn Maximum Sum Combinations with a step-by-step Heaps visualizer, JavaScript source code and a worked example. Practice priority queues and top k.

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 / 5Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": [
    1,
    4,
    2,
    3
  ],
  "b": [
    2,
    5,
    1,
    6
  ],
  "k": 4
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,b,k
},s)=>{
a.sort((x,y)=>y-x);
b.sort((x,y)=>y-x);
let q=[[a[0]+b[0],0,0]],seen=new Set(["0,0"]),o=[];
while(o.length<k&&q.length){
q.sort((a,b)=>b[0]-a[0]);
let [v,i,j]=q.shift();
o.push(v);
for(let [x,y] of [[i+1,j],[i,j+1]])if(x<a.length&&y<b.length&&!seen.has(x+","+y)){
seen.add(x+","+y);
q.push([a[x]+b[y],x,y])
}
s("Extract largest candidate",{
A:a,B:b,Frontier:q,Output:o
})
}
return o
};

Execution canvas

Active Changed
STEP 1

Extract largest candidate

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

A4 items
B4 items
Frontier2 rows
Output1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Heaps · Priority queues and top K

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

{
  "a": [
    1,
    4,
    2,
    3
  ],
  "b": [
    2,
    5,
    1,
    6
  ],
  "k": 4
}

Execution steps

  1. Extract largest candidate

Computed output

[
  10,
  9,
  9,
  8
]
JavaScript reference implementation
const solve = ({
  a,b,k
},s)=>{
  a.sort((x,y)=>y-x);
  b.sort((x,y)=>y-x);
  let q=[[a[0]+b[0],0,0]],seen=new Set(["0,0"]),o=[];
  while(o.length<k&&q.length){
    q.sort((a,b)=>b[0]-a[0]);
    let [v,i,j]=q.shift();
    o.push(v);
    for(let [x,y] of [[i+1,j],[i,j+1]])if(x<a.length&&y<b.length&&!seen.has(x+","+y)){
      seen.add(x+","+y);
      q.push([a[x]+b[y],x,y])
    }
    s("Extract largest candidate",{
      A:a,B:b,Frontier:q,Output:o
    })
  }
  return o
};

Continue learning

Practice related DSA questions in the same topic.