C++ simple, O(n) solution, space O(1)


  • 0
    T

    Here, a is the maximum treasure when robing a house, b is the maximum treasure when not robing a house.
    for a new house, if robbed its direct precedent should not be robbed. Then a(i)=b(i-1)+nums[i];
    If not robbed its direct precedent could be or not be robbed. So b(i)=max(a(i-1), b(i-1)).

    class Solution {
    public:
        int rob(vector<int>& nums) {
            int a=0, b=0;
            for (auto&&c: nums)
            {
                int x=a;
                a=b+c;
                b=max(x,b);
            }
            return max(a,b);
        }
    };
    

Log in to reply
 

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