function solution(food_times, k) {
let foods = food_times
.map((time, idx) => {
return { id: idx + 1, time }
})
.sort((a, b) => a.time - b.time)
while (foods.length) {
const foodCount = foods.length
const food = foods.shift()
if (foodCount * food.time <= k) {
k -= foodCount * food.time
foods = foods.map((f) => {
return { id: f.id, time: f.time - food.time }
})
} else {
foods.unshift(food)
const foodIdx = k === 0 ? 0 : k % foods.length
const sorted = foods.sort((a, b) => a.id - b.id)
return sorted[foodIdx].id
}
}
return -1
}
시간초과가 발생한다.
효율성 테스트 제한사항을 살펴보면 k = 2 x 10^13
이다.
걸리는 점
Number.MAX_SAFE_INTEGER
는 2 x 10^13
보다 크다.function solution(food_times, k) {
let foods = food_times
.map((time, idx) => {
return { id: idx + 1, time }
})
.sort((a, b) => a.time - b.time)
let eatAll = 0
for (let i = 0; i < foods.length; i++) {
const foodCount = foods.length - i
const food = foods[i]
if (foodCount * (food.time - eatAll) <= k) {
k -= foodCount * (food.time - eatAll)
eatAll = food.time
} else {
const foodIdx = k === 0 ? 0 : k % foodCount
const sorted = foods.slice(i).sort((a, b) => a.id - b.id)
return sorted[foodIdx].id
}
}
return -1
}
K
연산을 하던 부분을 삭제foods
를 queue
로 다루던 것을 for
문으로 변경