문제 주소
- https://programmers.co.kr/learn/courses/30/lessons/42897
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <string>
#include <vector>
using namespace std;
int solution(vector<int> money) {
int answer = 0;
int n = money.size();
vector<int> d1(n);
vector<int> d2(n);
// 첫번째 집을 털었을 때
// d1[i] = d1[i-2] + money[i]
// i-2 => 인접한 곳은 털 수 없으므로 i-2까지의 값을 더하기 위해
d1[0] = money[0];
d1[1] = d1[0]; // 인접한 i+1은 i값으로 대체
// 첫번째 집을 털지 않았을 때
d2[0] = 0;
d2[1] = money[1];
for (int i=2; i<n; i++) {
d1[i] = max(d1[i-2] + money[i], d1[i-1]);
d2[i] = max(d2[i-2] + money[i], d2[i-1]);
}
return max(d1[n-2], d2[n-1]);
}
아이디어
- 첫번째 집을 털었을 때와 털지 않았을 때를 구분
- 점화식은 동일 :
d[i] = d[i-2] + money[i]
- 초기 세팅값만 변경됨
- 첫번째 집을 털었을 경우
d1[0] = money[0]
-> 첫번째 집을 털었으므로 돈을 입력d1[1] = d1[0]
-> 인접한 i+1은d1[0]
으로 대체 (인접한 곳은 털 수 없다고 했으므로)
- 첫번째 집을 털지 않았을 경우
d2[0] = 0
-> 첫번째 집을 털지 않았으므로 0d2[1] = money[1]
-> 첫번째 집 이후의 i+1은 털 수 있으므로money[1]
- 점화식은 동일 :
Comments powered by Disqus.