Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 30 | 31 |
Tags
- 동적계획법
- 그리디
- 유니온 파인드
- 시뮬레이션
- 백트래킹
- Effective Java
- BFS
- swea
- 구현
- 이분탐색
- JUnit 5
- 프로그래머스
- 수학
- java
- 에라토스테네스의 체
- dfs
- 위상정렬
- mst
- Network
- 투 포인터
- 알고리즘
- 문자열
- 세그먼트 트리
- 후니의 쉽게 쓴 시스코 네트워킹
- 백준
- 완전탐색
- 스택
- CS
- 플로이드-와샬
- Kotlin
Archives
반갑습니다!
[프로그래머스] 스티커 모으기(2) 본문
풀이
[프로그래머스] 도둑질과 동일한 문제이다. 차이점이 있다면 N이 1인 경우 예외처리를 해줘야한다는 점이다.
코드
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int solution(vector<int> sticker){
int n = sticker.size();
if(n == 1) return sticker[0];
vector<vector<int>> dp(2, vector<int>(n, 0));
dp[0][0] = 0;
dp[1][0] = sticker[0];
for (int i = 1; i < n; i++) {
dp[0][i] = max(dp[0][i - 1], dp[0][i - 2] + sticker[i]);
dp[1][i] = max(dp[1][i - 1], dp[1][i - 2] + sticker[i]);
}
return max(dp[0][n - 1], dp[1][n - 2]);
}
Python3
def solution(sticker):
n = len(sticker)
if n == 1:
return sticker[0]
dp = [[0] * n for _ in range(2)]
dp[0][0] = 0
dp[1][0] = sticker[0]
for i in range(2):
for j in range(1, n):
dp[i][j] = max(dp[i][j - 1], dp[i][j - 2] + sticker[j])
answer = max(dp[0][-1], dp[1][-2])
return answer
'알고리즘 문제 풀이' 카테고리의 다른 글
[백준] 2458 키 순서 (0) | 2020.09.30 |
---|---|
[백준] 14496 그대, 그머가 되어 (0) | 2020.09.30 |
[프로그래머스] 도둑질 (0) | 2020.09.25 |
[백준] 18353 병사 배치하기 (0) | 2020.09.25 |
[백준] 2491 수열 (0) | 2020.09.25 |