https://leetcode.com/problems/house-robber-ii/
House Robber II - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
1. 시간복잡도 - O(n) : 똑같은 알고리즘(helper function) 2번 호출할 뿐임
2. 공간복잡도 - O(1) : don't need any extra data structure. just 변수 2개만 사용하고 있음.
class Solution(object):
def rob(self, nums):
return max(nums[0], self.helper(nums[1:]), self.helper(nums[:-1]))
def helper(self, nums):
rob1, rob2 = 0, 0
for n in nums:
newRob = max(rob1 + n, rob2)
rob1 = rob2
rob2 = newRob
return rob2
'알고리즘' 카테고리의 다른 글
[leetcode] 916. Word Subsets (0) | 2024.01.30 |
---|---|
[Algorithm] 217-Contains-Duplicate (1) | 2022.06.07 |
[Algorithm] min-cost-climbing-stairs 문제 (0) | 2022.05.21 |
[Algorithm] 편집 거리 (0) | 2022.05.12 |
[Algorithm] 금광 문제 (0) | 2022.04.27 |