- 난이도: Lv2
프로그래머스 링크: https://school.programmers.co.kr/learn/courses/30/lessons/389479
풀이 링크(GitHub): hayannn/CodingTest_Java/프로그래머스/2/서버 증설 횟수
풀이 시간 : 35분
활성 서버 추적
서버 반납 처리
import java.util.*;
class Solution {
public int solution(int[] players, int m, int k) {
int n = players.length;
int[] shutDownSchedule = new int[n + k]; // t+k 시점에 반납될 서버 수
int runningServers = 0; // 지금 돌고 있는 서버 수
int totalAdded = 0; // 총 증설된 서버 수(최종 값)
for (int t = 0; t < n; t++) {
// k 시간이 지난 후 반납될 서버 제거
runningServers -= shutDownSchedule[t];
// 추가 서버 수
int requiredServers = players[t] / m;
//부족한 만큼 증설
if (runningServers < requiredServers) {
int add = requiredServers - runningServers;
totalAdded += add;
runningServers += add;
// k 시간 후 서버 반납
if (t + k < shutDownSchedule.length) {
shutDownSchedule[t + k] += add;
}
}
}
return totalAdded;
}
}
import java.util.*;
class Solution {
public int solution(int[] requests, int maxUsersPerServer, int activeTime) {
int totalServersAdded = 0;
int[] servers = new int[requests.length + activeTime];
long activeCapacity = 0;
for (int time = 0; time < requests.length; time++) {
if (time - activeTime >= 0) {
activeCapacity -= (long) servers[time - activeTime] * maxUsersPerServer;
}
int currentRequest = requests[time];
if (activeCapacity >= currentRequest) continue;
long required = currentRequest - activeCapacity;
int serversToAdd = (int) ((required + maxUsersPerServer - 1) / maxUsersPerServer);
servers[time] = serversToAdd;
totalServersAdded += serversToAdd;
activeCapacity += (long) serversToAdd * maxUsersPerServer;
}
return totalServersAdded;
}
}
activeTime
이 발생되는 유효 범위가 의도와 다르게 계산되고 있음activeTime
이 지난 시점의 서버는 만료되니, 그 수만큼 처리 용량에서 빼자는 의도였지만 이 부분이 다소 모호하여 연산 오류가 나는 것으로 파악if (time - activeTime >= 0) {
activeCapacity -= (long) servers[time - activeTime] * maxUsersPerServer;
}
요청량은 시점별로 발생해야하나,activeCapacity
는 누적치처럼 유지됨
players[i]
는 순간 요청량인데, activeCapacity
는 "가상의 누적 처리 용량"처럼 처리되는 것activeCapacity
유효 서버 수 × 처리량
이 일치하지 않는 것k
시간 동안의 서버로 추적servers[t]
서버가 증설t
, t+1
, ..., t + k - 1
시간의 요청을 커버