Run Tasks with Concurrency Limit
JavaScript
Medium
4 views
Problem Description
Given n tasks durations (ms) and a limit k, simulate running tasks with max k parallel workers. Print total time taken.
Input Format
Line1: n k. Line2: n integers durations.
Output Format
One integer total time.
Official Solution
const fs=require('fs');const raw=fs.readFileSync(0,'utf8').trim();if(!raw)process.exit(0);const a=raw.split(/\\s+/).map(Number);let i=0;const n=a[i++],k=a[i++];const d=a.slice(i,i+n);if(n===0){process.stdout.write('0');process.exit(0);}const heap=[];const push=x=>{heap.push(x);let p=heap.length-1;while(p>0){let q=(p-1)>>1;if(heap[q]<=heap[p])break;[heap[q],heap[p]]=[heap[p],heap[q]];p=q;}};const pop=()=>{const top=heap[0];const last=heap.pop();if(heap.length){heap[0]=last;let p=0;for(;;){let l=p*2+1,r=l+1,sm=p;if(l<heap.length && heap[l]<heap[sm])sm=l;if(r<heap.length && heap[r]<heap[sm])sm=r;if(sm===p)break;[heap[p],heap[sm]]=[heap[sm],heap[p]];p=sm;}}return top;};let time=0;let idx=0;while(idx<n && heap.length<k){push(d[idx++]);}while(idx<n){time=pop();push(time+d[idx++]);}while(heap.length)time=pop();process.stdout.write(String(time));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!