https://school.programmers.co.kr/learn/courses/30/lessons/72414
청자들이 해당 동영상의 어떤 구간을 재생했는 지 알 수 있는 재생구간 기록을 구했고, 해당 기록을 바탕으로 공익광고가 삽입될 최적의 위치를 고를 수 있었습니다.
시청자들의 누적 재생시간이 가장 많이 나오는 곳에 공익광고를 삽입하려고 합니다. 이때, 공익광고가 들어갈 시작 시각을 구해서 return 하도록 solution 함수를 완성해주세요. 만약, 시청자들의 누적 재생시간이 가장 많은 곳이 여러 곳이라면, 그 중에서 가장 빠른 시작 시각을 return 하도록 합니다.
누적합을 이용하는 문제입니다.
누적 시청자 수를 보관하는 배열을 생성해 0초부터 각 초까지의 누적 시청 시간을 보관합니다.
슬라이딩 윈도우를 활용해 광고를 넣을 최적의 시점을 구합니다.
function solution(play_time, adv_time, logs) {
const toSec = (time) => {
const [h, m, s] = time.split(":").map(Number);
return h * 3600 + m * 60 + s;
}
const toTime = (sec) => {
const h = String(Math.floor(sec / 3600)).padStart(2, '0');
const m = String(Math.floor((sec % 3600) / 60)).padStart(2, '0');
const s = String(sec % 60).padStart(2, '0');
return `${h}:${m}:${s}`;
};
const play = toSec(play_time);
const adv = toSec(adv_time);
const timeline = Array(play + 2).fill(0);
// 시청자 변화 마킹
for (const log of logs) {
const [start, end] = log.split('-').map(toSec);
timeline[start] += 1;
timeline[end] -= 1;
}
// 누적 시청자 수
for (let i = 1; i <= play; i++) {
timeline[i] += timeline[i - 1];
}
// 누적 시청 시간
for (let i = 1; i <= play; i++) {
timeline[i] += timeline[i - 1];
}
// 최대 누적 시청 시간 구간 찾기
let maxTime = timeline[adv - 1];
let start = 0;
for (let i = adv; i <= play; i++) {
const cur = timeline[i] - timeline[i - adv];
if (cur > maxTime) {
maxTime = cur;
start = i - adv + 1;
}
}
return toTime(start);
}