본문 바로가기
알고리즘 문제/LeetCode

[LeetCode] 198. House Robber (C++)

by 에르주 2021. 12. 2.
반응형

Question 198.

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.
Example 1:

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.

Example 2:

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.

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 400

 

Sol)

해당 문제는 Dynamic Programming으로 주어진 배열이나 벡터값들을 차례대로 비교해가며 Max 값을 도출하는 문제이다.
예를 들어 Input nums 4번째 Index에서의 Max 값은
1. max[2] + a[4]
2. max[3]
값을 비교하여 max[4] 즉 4번째 Index의 max값이 되는 것이다.

class Solution {
    
public:
    int rob(vector<int>& nums) {
     
        int maxArraySize = nums.size();
    
        int* maxNum = new int[maxArraySize];
        
        maxNum[0] = nums[0];
        if(nums.size() < 2) return maxNum[0]; // size가 1개일 때 max는 0번째 Index
        
        maxNum[1] = max(nums[0], nums[1]);
        if(nums.size() < 3) return max(maxNum[0], maxNum[1]); // size가 2개일 때 0번째 또는 1번째 Index 중 max값이다.
        
        for(int i=2; i<nums.size(); i++) {
             
            maxNum[i] = max(maxNum[i-2]+nums[i], maxNum[i-1]);
        }
        
        return maxNum[maxArraySize-1];
    }
    
    int max(int a, int b){
        
        return a > b ? a:b;
    }
};




끝.

반응형

댓글