5-lines 0 ms C++ O(1) space c++ solution


  • 12
    M
    class Solution {
    public:
        int rob(vector<int>& nums) {
            int it1 = 0, it2 = 0;
            for (int i = 0; i < nums.size(); i++) {
                it1 = max(it1 + nums[i], it2);
                swap(it1, it2);
            }
            return it2;
        }
    };

  • 0
    J

    your answer is accepted and I have tested with many cases. Can you explain,thanks?


  • 1
    N

    Here is the reason, the DP formula that leads to the right answer:

    • M(k) = money at the kth house
    • P(0) = 0
    • P(1) = M(1)
    • P(k) = max(P(k−2) + M(k), P(k−1))

Log in to reply
 

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