|
| 1 | +""" |
| 2 | + You are a professional robber planning to rob houses along a street. Each |
| 3 | + house has a certain amount of money stashed, the only constraint stopping |
| 4 | + you from robbing each of them is that adjacent houses have security system |
| 5 | + connected and it will automatically contact the police if two adjacent |
| 6 | + houses were broken into on the same night. |
| 7 | +
|
| 8 | + Given a list of non-negative integers representing the amount of money of |
| 9 | + each house, determine the maximum amount of money you can rob tonight |
| 10 | + without alerting the police. |
| 11 | +
|
| 12 | + Example: |
| 13 | + Input: nums = [1,2,3,1] |
| 14 | + Output: 4 |
| 15 | + Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). |
| 16 | + Total amount you can rob = 1 + 3 = 4. |
| 17 | +
|
| 18 | + Example: |
| 19 | + Input: nums = [2,7,9,3,1] |
| 20 | + Output: 12 |
| 21 | + Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and |
| 22 | + rob house 5 (money = 1). |
| 23 | + Total amount you can rob = 2 + 9 + 1 = 12. |
| 24 | +
|
| 25 | + Constraints: |
| 26 | + - 0 <= nums.length <= 100 |
| 27 | + - 0 <= nums[i] <= 400 |
| 28 | +""" |
| 29 | +#Difficulty: Easy |
| 30 | +#69 / 69 test cases passed. |
| 31 | +#Runtime: 40 ms |
| 32 | +#Memory Usage: 13.8 MB |
| 33 | + |
| 34 | +#Runtime: 40 ms, faster than 27.94% of Python3 online submissions for House Robber. |
| 35 | +#Memory Usage: 13.8 MB, less than 69.22% of Python3 online submissions for House Robber. |
| 36 | + |
| 37 | +class Solution: |
| 38 | + def rob(self, nums: List[int]) -> int: |
| 39 | + odd_num = 0 |
| 40 | + even_num = 0 |
| 41 | + for i in range(len(nums)): |
| 42 | + if i % 2: |
| 43 | + odd_num += nums[i] |
| 44 | + odd_num = max(odd_num, even_num) |
| 45 | + else: |
| 46 | + even_num += nums[i] |
| 47 | + even_num = max(odd_num, even_num) |
| 48 | + return max(odd_num, even_num) |
0 commit comments