打家劫舍
This commit is contained in:
parent
95ca64dc6c
commit
46dc5e9b3d
@ -357,6 +357,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
|
||||
|
||||
- LeetCode 974. 和可被 K 整除的子数组 <https://leetcode-cn.com/problems/subarray-sums-divisible-by-k/>
|
||||
|
||||
- [打家劫舍](src/array/house-robber.js)
|
||||
|
||||
- LeetCode 198. 打家劫舍 <https://leetcode-cn.com/problems/house-robber/>
|
||||
- LintCode 392. 打劫房屋 <https://www.lintcode.com/problem/house-robber/description>
|
||||
|
||||
## 栈
|
||||
|
||||
- [最大矩阵](src/stack/maximal-rectangle.js)
|
||||
|
18
src/array/house-robber.js
Normal file
18
src/array/house-robber.js
Normal file
@ -0,0 +1,18 @@
|
||||
/**
|
||||
* @param {number[]} nums
|
||||
* @return {number}
|
||||
*/
|
||||
export const rob = function (nums) {
|
||||
if (!nums) return 0
|
||||
const len = nums.length
|
||||
if (len === 0) return 0
|
||||
if (len === 1) return nums[0]
|
||||
|
||||
let first = nums[0]; let second = Math.max(nums[0], nums[1])
|
||||
for (let i = 2; i < len; i++) {
|
||||
const temp = second
|
||||
second = Math.max(first + nums[i], second)
|
||||
first = temp
|
||||
}
|
||||
return second
|
||||
}
|
7
test/array/house-robber.test.js
Normal file
7
test/array/house-robber.test.js
Normal file
@ -0,0 +1,7 @@
|
||||
import { rob } from '../../src/array/house-robber'
|
||||
|
||||
test('打家劫舍', () => {
|
||||
expect(rob([1, 2, 3, 1])).toBe(4)
|
||||
expect(rob([2, 7, 9, 3, 1])).toBe(12)
|
||||
expect(rob([828, 125, 740, 724, 983, 321, 773, 678, 841, 842, 875, 377, 674, 144, 340, 467, 625, 916, 463, 922, 255, 662, 692, 123, 778, 766, 254, 559, 480, 483, 904, 60, 305, 966, 872, 935, 626, 691, 832, 998, 508, 657, 215, 162, 858, 179, 869, 674, 452, 158, 520, 138, 847, 452, 764, 995, 600, 568, 92, 496, 533, 404, 186, 345, 304, 420, 181, 73, 547, 281, 374, 376, 454, 438, 553, 929, 140, 298, 451, 674, 91, 531, 685, 862, 446, 262, 477, 573, 627, 624, 814, 103, 294, 388])).toBe(29123)
|
||||
})
|
Loading…
Reference in New Issue
Block a user