항해99, 5주차 집 도둑

Jang Seok Woo·2022년 2월 13일
0

알고리즘

목록 보기
68/74

Today I learned
2022/02/09

회고록


2/09

항해 99, 알고리즘 4주차(항해 5주차)

교재 : 파이썬 알고리즘 인터뷰 / 이것이 코딩테스트다(동빈좌)

다이나믹 프로그래밍

1. 이론

이론 정리 포스팅 글(내 벨로그)

https://velog.io/@jsw4215/%ED%95%AD%ED%95%B499-5%EC%A3%BC%EC%B0%A8-%EB%8B%A4%EC%9D%B4%EB%82%98%EB%AF%B9%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D

2. 문제

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses 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.

https://leetcode.com/problems/house-robber/

3. MySol

  • DP btm-up memoization
n = [2,1]

if len(n) == 1:
    print(f'{n[0]}')

d = [0]*len(n)

d[0] = n[0]
d[1] = max(n[0],n[1])

for i in range(2,len(n)):
    if d[i-1] > n[i] + d[i-2]:
        d[i] = d[i-1]
    else:
        d[i] = n[i] + d[i-2]


print(f'{d[len(n)-1]}')

4. 배운 점

  • DP
  • 바텀업 방식으로 메모이제이션 구현

5. 총평

DP 알고리즘 익히기

profile
https://github.com/jsw4215

0개의 댓글