forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain3.cpp
More file actions
40 lines (30 loc) · 796 Bytes
/
main3.cpp
File metadata and controls
40 lines (30 loc) · 796 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/// Source : https://leetcode.com/problems/house-robber/description/
/// Author : liuyubobobo
/// Time : 2017-11-19
#include <iostream>
#include <vector>
using namespace std;
/// Dynamic Programming, with O(1) space
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
if(n == 0)
return 0;
int preMax = 0, curMax = 0;
for(int i = n - 1 ; i >= 0 ; i --) {
int temp = curMax;
curMax = max(curMax, nums[i] + preMax);
preMax = temp;
}
return curMax;
}
};
int main() {
int nums[] = {2, 1};
vector<int> vec(nums, nums + sizeof(nums)/sizeof(int));
cout << Solution().rob(vec) << endl;
return 0;
}