Simple C++ DP solution WITH explanations


  • 0
    U

    Basic idea: simple DP, T(k) denotes max money for nums[1..k] WITH k-th house robbed.
    recursive function: T(k) = max(T(i) + nums[k]) where i = 1...k-2

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

Log in to reply
 

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