본문 바로가기
LeetCode/Top Interview Q. - Easy

LeetCode. House Robber [Dynamic Programming]

by 벤진[Benzene] 2020. 6. 12.

Problem:

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 system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine 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.

 

-Summary-

Bottom-up solve with dynamic programming

1. Think about 3 base cases we have.

- If the house does not exist, we always return 0.

- If only 1 house exists, we choose that house.

- If two houses exist, we choose the bigger one.

- If three houses exists, then we choose current house value + two previous index value or 1 previous index value.

ex) [1,2,3] --> choose between 2 and 1+3 = 4 

     [2,6,5] --> choose between 6 and 2+5 = 7

     [100,1,100] ---> choose between 1 and 100+100 = 200

2. Keep save this value in dp list, and choose the best option until the loop ends.

3. return the maximum amount of money.

 

모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]

댓글