| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
- 알고리즘스터디
- 알고리즘
- RxJS 함수형 프로그래밍
- 달래스터디
- RxJS 마블 다이어그램
- React 리렌더링 최적화
- leetcode
- 스쿼드조직
- RxJS 결합 오퍼레이터
- Climbing Stairs
- useCallback 성능 최적화
- DaleStudy
- 협업문화
- 개발자커뮤니케이션
- React useCallback 사용법
- React useMemo 사용법
- useMemo 성능 최적화
- React 성능 최적화 방법
- 자바스크립트 고차 함수 vs Observable
- RxJS 변환 오퍼레이터
- leedcode
- RxJS 생성 오퍼레이터
- RxJS 멀티캐스팅
- React useEffect 안티패턴
- contains duplicate
- Observable vs Array
- Blind75
- RxJS 오퍼레이터
- RxJS 에러 처리
- React hooks 남용 사례
- Today
- Total
수쿵의 IT월드
DaleStudy | Leetcode Study 1주차 - House Robber 본문

문제
You are a professional robber planning to rob houses along a street. Each houst has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houst have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
Constraints:
- 1 <= nums.length <= 100
- 0 <= nums[i] <= 400
풀이
DP(Dynamic Programming)는 복잡한 문제를 여러 하위 문제로 나누고, 이전 결과를 저장해서 중복 계산을 피하는 최적화 기법입니다.
일반적으로는 최대값/최소값, 개수 세기, 경로 탐색과 같은 문제에서 많이 사용되며,
예를 들어 “근접한 항목을 선택하지 않고 최대 합을 구하는 문제”처럼 결정 간 제약 조건이 있는 문제에도 자주 사용됩니다.
먼저 알고리즘 문제를 풀 때는 문제를 단계별로 어떻게 풀 건지 설계하는게 중요한데, 이 문제는 3부분으로 나눠서 볼 수 있습니다.
- 주어진 배열과 동일한 크기를 가진 배열을 생성합니다.
- 그 배열에는 인접하지 않은 원소를 더한 값과 이전의 인덱스의 값 중 큰 값을 비교해서 큰 값을 추가합니다.
- 배열의 마지막 원소를 리턴하면 됩니다.
function rob(nums: number[]): number {
if (nums.length === 0) { return 0; }
if (nums.length === 1) { return nums[0]; }
const maxSums = nums.slice();
maxSums[1] = Math.max(nums[0], nums[1]);
for(let i=2; i<nums.length; i++) {
maxSums[i] = Math.max(maxSums[i-1], (maxSums[i-2] + nums[i]))
}
return maxSums[maxSums.length - 1]
};