-
[릿코드/javascript] 198. House Robber카테고리 없음 2023. 3. 31. 10:10
문제
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.
var rob = function(nums) { //연속으로 하면 안됨!!! 즉 0이면 2이상이어야함. for(let i=nums.length-3;i>=0;i--){ nums[i]+=Math.max(nums[i+2],nums[i+3])||nums[i+2] } return Math.max(...nums) };
연속되지않는 nums[idx]를 더했을때 가장 큰 값을 찾아야한다.
뒤에서부터 잘라서 처음엔 요소가 3개인배열 그다음엔 4개인배열 5개의 배열...이런식으로 늘려갔다.
연속되지않아야하므로 i+2이상의 값을 구해야하는데. i+3에서 더 클 수 있으므로 i+3이 더 크면 i+3을 더한다.
누적으로 더했으므로 i+4는 고려할 필요가 없다.