function solution(n, works) {
let answer = 0;
if (works.reduce((a,b)=>a+b)<=n){
answer=0;
return answer;
}
let leftHours=n;
let worksLeft=works.slice().sort((a,b)=>a-b);
while(leftHours>0){
let max=worksLeft[worksLeft.length-1]
for (let i=0;i<worksLeft.length;i++){
if (worksLeft[i]>=max){
worksLeft[i]-=1;
leftHours-=1;
}
if (leftHours<=0){
break;
}
}
}
answer=worksLeft.reduce((a, b)=>a+Math.pow(b,2),0)
return answer;
}