《leetCode》:House Robber II

题目

Note: This is an extension of House Robber.

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

思路

受上一题思路的影响,由于此时有环,意味着第一个元素和最后一个元素不能同时出现,因此,我们可以将数组分成两部分,第一部分就是除去最后一个元素构成的数组产生一个最大值max1,第二部分就是除去第一个元素构成的数组产生一个最大值max2.最后的结果就是max(max1,max2).

int max(int a,int b){
    return a>b?a:b;
}
int maxInArr(int *nums,int numsSize){
    if(nums==NULL||numsSize<1){
        return 0;
    }
    int maxValue=0;
    for(int i=0;i<numsSize;i++){
        if(maxValue<nums[i]){
            maxValue=nums[i];
        }
    }
    return maxValue;
}
int robHelper(int *nums,int numsSize){
    if(nums==NULL||numsSize<1){
        return 0;
    }
    int *result=(int *)malloc(numsSize*sizeof(int));
    if(result==NULL){
        exit(EXIT_FAILURE);
    } 
    memset(result,0,numsSize*sizeof(int));//初始化为0 
    for(int i=numsSize-1;i>=0;i--){
        if(i==numsSize-1){
            result[numsSize-1]=nums[numsSize-1];
        }
        else if(i==numsSize-2){
            result[numsSize-2]=nums[numsSize-2];
        }
        else if(i==numsSize-3){
            result[i]=nums[i]+nums[i+2];
        }
        else {
            result[i]=nums[i]+max(result[i+2],result[i+3]);
        }
    }
    return max(result[0],result[1]);
}

int rob(int* nums, int numsSize) {  
    if(nums==NULL||numsSize<1){
        return 0;
    }
    if(numsSize<=3){
        return maxInArr(nums,numsSize);
    }
    int res1=robHelper(nums,numsSize-1);//第一个元素可能参与产生最大值 
    int res2=robHelper(nums+1,numsSize-1);//最后一个元素可能参与产生最大值 
    return max(res1,res2); 
}

你可能感兴趣的:(LeetCode,house,Robber)