https://school.programmers.co.kr/learn/courses/30/lessons/12979
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
접근 방법
- 기지국이 필요한 구간의 길이 = d 라고할때, 이 구간에 필요한 기지국의 개수는
- d % w == 0 이면 d / w 개가 필요하다
- 아니면 d / w + 1개가 필요하다
- 그렇다면 슬라이딩 윈도우로 필요한 구간을 찾고 "ans += fnc(구간)" 형태로 값을 더해주면 되겠다 ! => 시간 초과 발생
- 사실 구간은 solution 함수의 파라미터 만으로 알 수 있다
- 0 ~ stations[0]-w-1 , stations[0]+w+1 ~ stations[2]-w-1, ... , stations[stations.length-1]+w+1 ~ n
코드
class Solution {
public int solution(int n, int[] stations, int w) {
int ans = 0;
ans += getWidth(1, stations[0] - w - 1, 2*w+1);
for(int i = 1; i < stations.length ; i++){
ans += getWidth(stations[i-1]+w+1, stations[i]-w-1, 2*w+1);
}
ans += getWidth(stations[stations.length-1]+w+1, n, 2*w+1);
return ans;
}
int getWidth(int l,int r,int w){
int num = r - l + 1;
if(num <= 0) return 0;
if(num % w == 0) return num / w;
return num / w + 1;
}
}
'Algorithm' 카테고리의 다른 글
[프로그래머스] LV 3 불량사용자 (0) | 2024.10.28 |
---|---|
[프로그래머스] LV 2 마법의 엘리베이터 (0) | 2024.10.26 |
[프로그래머스] LV 3 스티커 모으기(2) (2) | 2024.10.26 |
[프로그래머스] LV 2 두 큐 합 같게 만들기 (0) | 2024.10.26 |
[프로그래머스] LV 2 쿼드압축 후 개수 세기 (0) | 2024.10.24 |