[LeetCode] House Robber

198. House Robber

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 systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

  • new solution updated 2022.02.03
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int rob(vector<int>& nums) {
int odd = 0, even = 0;
for(int i = 0; i < nums.size(); i++) {
if(i&1) odd = max(even, odd + nums[i]);
else even = max(odd, even + nums[i]);
}
return max(odd,even);
}
};
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int rob(vector<int>& nums) {
int r1(nums[0]), r2(0), tmp;
for(int i = 1; i < nums.size(); i++) {
tmp = r2 + nums[i];
r2 = max(r1, r2);
r1 = tmp;
}
return max(r1, r2);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/29/PS/LeetCode/house-robber/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.