mirror of
https://github.com/devenperez/leetcode.git
synced 2026-06-13 03:27:07 +00:00
Time: 0 ms (100%), Space: 18 MB (13.14%) - LeetHub
This commit is contained in:
@@ -1,24 +1,16 @@
|
||||
class Solution(object):
|
||||
def rob(self, nums):
|
||||
"""
|
||||
:type nums: List[int]
|
||||
:rtype: int
|
||||
"""
|
||||
class Solution:
|
||||
def rob(self, nums: List[int]) -> int:
|
||||
n = len(nums)
|
||||
dp = [0] * n
|
||||
|
||||
if len(nums) < 3:
|
||||
return max(nums)
|
||||
if n >= 1:
|
||||
dp[0] = nums[0]
|
||||
if n >= 2:
|
||||
dp[1] = max(nums[0], nums[1])
|
||||
if n >= 3:
|
||||
dp[2] = max(nums[0] + nums[2], nums[1])
|
||||
|
||||
# Subproblem: only nums 0 to i exist and i is always robbed
|
||||
dp = [0] * 3 # Optimized to only hold the last 3 entries
|
||||
for i in range(3, n):
|
||||
dp[i] = max(nums[i] + dp[i - 2], nums[i - 1] + dp[i - 3])
|
||||
|
||||
dp[0] = nums[0]
|
||||
dp[1] = nums[1]
|
||||
dp[2] = nums[2] + nums[0]
|
||||
|
||||
|
||||
for i in range(3, len(nums)):
|
||||
x = i % 3
|
||||
dp[x] = nums[i] + max(dp[(x - 2) % 3], dp[x])
|
||||
|
||||
return max(dp)
|
||||
|
||||
return dp[-1]
|
||||
Reference in New Issue
Block a user