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.
1 /************************************************************************* 2 > File Name: LeetCode213.c 3 > Author: Juntaran 4 > Mail: [email protected] 5 > Created Time: Wed 11 May 2016 17:11:02 PM CST 6 ************************************************************************/ 7 8 /************************************************************************* 9 10 House Robber II 11 12 Note: This is an extension of House Robber. 13 14 After robbing those houses on that street, 15 the thief has found himself a new place for his thievery 16 so that he will not get too much attention. 17 This time, all houses at this place are arranged in a circle. 18 That means the first house is the neighbor of the last one. 19 Meanwhile, the security system for these houses remain the same as 20 for those in the previous street. 21 22 Given a list of non-negative integers representing 23 the amount of money of each house, 24 determine the maximum amount of money you can rob tonight 25 without alerting the police. 26 27 ************************************************************************/ 28 29 #include <stdio.h> 30 31 /* 32 跟198的区别在于现在是一个环形,首尾不能同时get 33 所以分成两种情况: 34 1:从头取到尾-1 35 2:从头+1取到尾 36 rob过程相同,然后比较两种情况大小 37 */ 38 int rob( int* nums, int numsSize ) 39 { 40 if( numsSize == 0 ) 41 { 42 return 0; 43 } 44 if( numsSize == 1 ) 45 { 46 return nums[0]; 47 } 48 49 int max = 0; 50 int prev1 = 0; 51 int prev2 = 0; 52 53 int i, temp; 54 55 temp = 0; 56 prev1 = 0; 57 prev2 = 0; 58 for( i=0; i<=numsSize-2; i++ ) 59 { 60 temp = prev1; 61 prev1 = (prev2+nums[i])>prev1 ? (prev2+nums[i]) : prev1; 62 prev2 = temp; 63 } 64 max = prev1; 65 66 temp = 0; 67 prev1 = 0; 68 prev2 = 0; 69 for( i=1; i<=numsSize-1; i++ ) 70 { 71 temp = prev1; 72 prev1 = (prev2+nums[i])>prev1 ? (prev2+nums[i]) : prev1; 73 prev2 = temp; 74 } 75 max = max>prev1 ? max : prev1; 76 77 return max; 78 } 79 80 81 int main() 82 { 83 int nums[] = { 2,1,1,4,7,3,0 }; 84 int numsSize = 7; 85 86 int ret = rob( nums, numsSize ); 87 printf("%d\n", ret); 88 return 0; 89 }
时间: 2024-10-05 13:37:57