Skip to content

Commit a664138

Browse files
author
lewis617
committed
Add house-robber
1 parent 1a0086f commit a664138

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

ArrayList/ArrayList.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,29 @@ function ArrayList() {
162162
findNSum(array, M, N, [], results);
163163
return results;
164164
};
165+
166+
var rob = function (array) {
167+
var last = 0,
168+
now = 0;
169+
for (var i = 0; i < array.length; i++) {
170+
var temp = last;
171+
last = now;
172+
now = Math.max(temp + array[i], now);
173+
}
174+
175+
return now;
176+
};
177+
178+
this.simpleRob = function () {
179+
return rob(array);
180+
};
181+
182+
this.circleRob = function () {
183+
if (array.length === 1) {
184+
return array[0];
185+
}
186+
return Math.max(rob(array.slice(1)), rob(array.slice(0, array.length - 1)));
187+
}
165188
}
166189

167190
module.exports = ArrayList;

ArrayList/ArrayList.test.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,18 @@ test('ArrayList', function () {
4545
expect(array.NSum(2, 6)).toEqual([[1, 5], [2, 4]]);
4646
expect(array.NSum(3, 7)).toEqual([[1, 2, 4]]);
4747
expect(array.NSum(4, 14)).toEqual([[2, 3, 4, 5]]);
48+
49+
function createRobArray() {
50+
var array = new ArrayList();
51+
array.insert(2);
52+
array.insert(0);
53+
array.insert(0);
54+
array.insert(4);
55+
array.insert(5);
56+
return array;
57+
}
58+
59+
array = createRobArray();
60+
expect(array.simpleRob()).toBe(7);
61+
expect(array.circleRob()).toBe(6);
4862
});

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@
3838

3939
[数组搜索算法题:求和为定值的多个数](https://lewis617.github.io/2017/03/09/n-sum/)
4040

41+
[动态规划算法题:打家劫舍](https://lewis617.github.io/2017/03/10/house-robber/)
42+
4143
## 其他教程
4244

4345
[React+Redux系列教程](https://github.com/lewis617/react-redux-tutorial)

0 commit comments

Comments
 (0)