No extra space need, reuse nums space


  • 0
    L

    Reuse nums to store the temp value.

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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.