func _rob(nums []int)int { first, second := nums[0], max(nums[0], nums[1]) for _, v := range nums[2:] { first, second = second, max(first+v, second) } return second }
funcrob(nums []int)int { n := len(nums) if n == 1 { return nums[0] } if n == 2 { return max(nums[0], nums[1]) } return max(_rob(nums[:n-1]), _rob(nums[1:])) }
funcmax(a, b int)int { if a > b { return a } return b }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: defrob(self, nums: List[int]) -> int: defrobRange(start: int, end: int) -> int: first = nums[start] second = max(nums[start], nums[start + 1]) for i inrange(start + 2, end + 1): first, second = second, max(first + nums[i], second) return second length = len(nums) if length == 1: return nums[0] elif length == 2: returnmax(nums[0], nums[1]) else: returnmax(robRange(0, length - 2), robRange(1, length - 1))
classSolution { public: introbRange(vector<int>& nums, int start, int end){ int first = nums[start], second = max(nums[start], nums[start + 1]); for (int i = start + 2; i <= end; i++) { int temp = second; second = max(first + nums[i], second); first = temp; } return second; }
introbRange(int* nums, int start, int end) { int first = nums[start], second = fmax(nums[start], nums[start + 1]); for (int i = start + 2; i <= end; i++) { int temp = second; second = fmax(first + nums[i], second); first = temp; } return second; }