Sunday, April 5, 2015

House Robber

Problem:
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.


Solution:

Recursive:
class Solution {
public:
    int rob(vector<int> &num) {
        int size = num.size();
        
        if (size == 0)
            return 0;
        else if (size == 1)
            return num[0];
        else if (size == 2)
            return max(num[0], num[1]);
        else if (size == 3)
            return max(num[0] + num[2], num[1]);
        else {
            vector<int> temp1 = num;
            vector<int> temp2 = num;
            
            temp1.erase(temp1.begin(), temp1.begin() + 2);
            temp2.erase(temp2.begin(), temp2.begin() + 3);
            
            return max(num[0] + rob(temp1), num[1] + rob(temp2));
        }
    }
};

Optimal one:
class Solution {
public:
    int rob(vector<int> &num) {
       vector<int> result;
       int size = num.size();
       if (size == 0)
            return 0;
        result.push_back(num[0]);
        if (size > 1)
            result.push_back(max(num[0], num[1]));
        
        for (int i = 2; i < size; i++) {
            int temp = num[i] + result[i - 2];
            result.push_back(max(result[i-1], temp));
        }
        return result[result.size() - 1];
    }
};

===== No extra space =====

class Solution {
public:
    int rob(vector<int>& nums) {
        int size = nums.size();
        if (size == 0) {
            return 0;
        } else if (size == 1) {
            return nums[0];
        } else {
            for (int i = 1; i < size; i++) {
                if (i == 1) {
                    nums[1] = max(nums[0], nums[1]);
                } else {
                    nums[i] = max(nums[i - 2] + nums[i], nums[i - 1]);
                }
            }
        }
        return nums[size - 1];
    }
};

No comments:

Post a Comment