C++ easy to understand, And a llittle problem


  • 0
    class Solution {
    public:
        int rob(vector<int>& nums) {
            if(nums.size() == 0) return 0;
            if(nums.size() == 1) return max(0, nums[0]);
          // if(nums.size() == 2) return 0;
            int size = nums.size();
            
            int a = 0, b = 0;
            int maxFront;
            int maxLast;
            
            for(int i = 0; i < size - 1; i ++) {
                if(i % 2 == 0)
                    a = max(b, a+nums[i]);
                else
                    b = max(a, b+nums[i]);
            }
            maxFront = max(a, b);
            
            
            a = 0; b = 0;
            
            for(int i = size - 1; i >= 1; i--) {
                if(i % 2 == 0)
                    a = max(b, a+nums[i]);
                else
                    b = max(a, b+nums[i]);
            }
            
            maxLast = max(a, b);
            
    
            return max(maxFront, maxLast);
        }
    };
    

    There are two options, if you want the first element, then the last one you can not consider. If you want the last one, you can not choose the first one.

    In my program, there is such a line if(nums.size() == 2) return 0;. I think if there are only two house, you can not rob any one.


Log in to reply
 

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