?LeetCode刷題實(shí)戰(zhàn)213:打家劫舍 II
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.
題意
示例
示例 1:
輸入:nums = [2,3,2]
輸出:3
解釋:你不能先偷竊 1 號房屋(金額 = 2),然后偷竊 3 號房屋(金額 = 2), 因?yàn)樗麄兪窍噜彽摹?br mpa-from-tpl="t">
示例 2:
輸入:nums = [1,2,3,1]
輸出:4
解釋:你可以先偷竊 1 號房屋(金額 = 1),然后偷竊 3 號房屋(金額 = 3)。
偷竊到的最高金額 = 1 + 3 = 4 。
示例 3:
輸入:nums = [0]
輸出:0
提示:
1 <= nums.length <= 100
0 <= nums[i] <= 1000
解題
var rob = function(nums) {
//特殊情況
const len = nums.length
if (len === 0) return 0
if (len === 1) return nums[0]
if (len === 2) return Math.max(nums[0], nums[1])
const rob = function(nums, start, end) {
let pMax = nums[start]
let cMax = Math.max(pMax, nums[start + 1])
for (let i = start + 2; i <= end; i++) {
console.log(i,cMax,pMax)
let tmp = cMax
cMax = Math.max((pMax +nums[i]), cMax)
pMax = tmp
}
return cMax
}
return Math.max(rob(nums, 0, len-2), rob(nums, 1, len-1))
};
LeetCode1-200題匯總,希望對你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)201:數(shù)字范圍按位與
LeetCode刷題實(shí)戰(zhàn)202:快樂數(shù)
LeetCode刷題實(shí)戰(zhàn)203:移除鏈表元素
LeetCode刷題實(shí)戰(zhàn)204:計(jì)數(shù)質(zhì)數(shù)
LeetCode刷題實(shí)戰(zhàn)205:同構(gòu)字符串
LeetCode刷題實(shí)戰(zhàn)206:反轉(zhuǎn)鏈表
LeetCode刷題實(shí)戰(zhàn)207:課程表
LeetCode刷題實(shí)戰(zhàn)208:實(shí)現(xiàn) Trie (前綴樹)
LeetCode刷題實(shí)戰(zhàn)209:長度最小的子數(shù)組
LeetCode刷題實(shí)戰(zhàn)210:課程表 II
LeetCode刷題實(shí)戰(zhàn)211:添加與搜索單詞
LeetCode刷題實(shí)戰(zhàn)212:單詞搜索 II
