[LeetCode] House Robber (JS)

nRecode·2021년 2월 3일
0

Algorithm

목록 보기
34/48

문제

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 system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

입출력 예
Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.

Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.

접근

nums의 길이가 1일 경우 첫번째 요소를 return하고 길이가 2이면 둘 중 가장 큰수를 return합니다.
그리고 계속 큰 수를 찾는 방법으로 값을 계속 저장 시켜놓고 Max값을 비교하면서 더하는 방법을 사용합니다.

twoBf와 현재인덱스의 값을 합친것과 oneBf를 비교해서 더 큰 것이 현재 인덱에서 가장 큰 합이 됩니다.

풀이

var rob = function(nums) {
    if(nums.length === 0) return 0;
    if(nums.length === 1) return nums[0];
    if(nums.length === 2) return Math.max(nums[0], nums[1]);
    
    let twoBf = nums[0];
    let oneBf = Math.max(nums[0], nums[1]);
    
    for(let i = 2; i < nums.length; i++){
        let curVal = Math.max(twoBf + nums[i], oneBf);
        twoBf = oneBf;
        oneBf = curVal;
    }
    
    return oneBf;
};
profile
안정성, 확장성 있는 서버를 구축하고 가꾸는 개발자를 목표로 공부하고 있습니다. 🤔🤔🤔🤔 부족하기에 맞지 않는 내용이 있을 수 있습니다. 가감없이 피드백 해주시면 정말 감사하겠습니다..🙏

0개의 댓글