C 0ms solution in O(1) space


  • 0
    S
    int find(int *nums, int left, int right){
        if(left>right)
            return 0;
        int i, incl=0, excl=0,temp;
        for(i=left; i<=right; i++){
            temp = incl;
            incl = excl + nums[i];
            excl = temp>excl? temp: excl;
        }
        return incl> excl? incl: excl;
    }
    
    int rob(int* nums, int numsSize) {
        if(numsSize ==1)
            return nums[0];
        int first = find(nums, 0, numsSize-2);
        int last = find(nums, 1, numsSize-1);
        return first> last? first: last;
    }

Log in to reply
 

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