Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions 198_house_robber/problem.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
## 問題: [198. House Robber](https://leetcode.com/problems/house-robber/description/)
25 changes: 25 additions & 0 deletions 198_house_robber/step1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Step 1

- $house(n)$まで訪れた時の最大の額$maxAmount(n)$は、$max(house(n) + maxAmount(n-2), maxAmount(n-1))$である

```python
class Solution:
def rob(self, nums: List[int]) -> int:
# 問題の制約でnumsのサイズが1以上は保証されているので、0は考慮しない
if len(nums) == 1:
return nums[0]
if len(nums) == 2:
return max(nums[0], nums[1])
max_amount_prev_2 = nums[0]
max_amount_prev_1 = max(nums[0], nums[1])
for i in range(2, len(nums)):
max_amount = max(max_amount_prev_1, nums[i] + max_amount_prev_2)
max_amount_prev_2 = max_amount_prev_1
max_amount_prev_1 = max_amount
return max_amount_prev_1

```

時間計算量: $O(n)$

空間計算量: $O(1)$
23 changes: 23 additions & 0 deletions 198_house_robber/step2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Step 2

```python
class Solution:
def rob(self, nums: List[int]) -> int:
# 問題の制約でnumsのサイズが1以上は保証されているので、0は考慮しない
if len(nums) == 1:
return nums[0]
if len(nums) == 2:
return max(nums[0], nums[1])
max_amount_prev_2 = nums[0]
max_amount_prev_1 = max(nums[0], nums[1])
for i in range(2, len(nums)):
max_amount = max(max_amount_prev_1, nums[i] + max_amount_prev_2)
max_amount_prev_2 = max_amount_prev_1
max_amount_prev_1 = max_amount
return max_amount_prev_1

```

時間計算量: $O(n)$

空間計算量: $O(1)$
24 changes: 24 additions & 0 deletions 198_house_robber/step3.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Step 3

```python
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
if len(nums) == 2:
return max(nums[0], nums[1])
Comment on lines +6 to +9
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

これが良いのかはわかりませんが、まとめて書くこともできますね

if len(nums) <= 2:
    return max(nums)

max_amount_prev_2 = nums[0]
max_amount_prev_1 = max(nums[0], nums[1])

for i in range(2, len(nums)):
max_amount = max(max_amount_prev_1, nums[i] + max_amount_prev_2)
max_amount_prev_2 = max_amount_prev_1
max_amount_prev_1 = max_amount
return max_amount_prev_1
```

1回目: 1分 46秒

2回目: 1分 58秒

3回目: 1分 47秒