Short C++ code, very easy to understand


  • 1
    G
    class Solution {
    public:
        int rob(vector<int>& nums) {
            int bestSoFarInclude = 0, bestSoFarExclude = 0;
            for (int i = 0; i < nums.size(); i++) {
                int temp = bestSoFarInclude;
                bestSoFarInclude = bestSoFarExclude + nums[i];
                bestSoFarExclude = temp > bestSoFarExclude ? temp : bestSoFarExclude;
            }
            return bestSoFarInclude > bestSoFarExclude ? bestSoFarInclude : bestSoFarExclude;
        }
    };

Log in to reply
 

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