You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.
1 2 3 4 5 6 7 8 9 10 11 |
func rob(_ nums: [Int]) -> Int { if nums.count < 1 { return nums.first ?? 0 } var lm = 0, gm = 0 for i in 0..<nums.count { let t = lm lm = gm gm = max(gm, t + nums[i]) } return gm } |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼