LeetCode 213

时间:2023-03-08 16:47:25

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.

 /*************************************************************************
> File Name: LeetCode213.c
> Author: Juntaran
> Mail: JuntaranMail@gmail.com
> Created Time: Wed 11 May 2016 17:11:02 PM CST
************************************************************************/ /************************************************************************* 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. ************************************************************************/ #include <stdio.h> /*
跟198的区别在于现在是一个环形,首尾不能同时get
所以分成两种情况:
1:从头取到尾-1
2:从头+1取到尾
rob过程相同,然后比较两种情况大小
*/
int rob( int* nums, int numsSize )
{
if( numsSize == )
{
return ;
}
if( numsSize == )
{
return nums[];
} int max = ;
int prev1 = ;
int prev2 = ; int i, temp; temp = ;
prev1 = ;
prev2 = ;
for( i=; i<=numsSize-; i++ )
{
temp = prev1;
prev1 = (prev2+nums[i])>prev1 ? (prev2+nums[i]) : prev1;
prev2 = temp;
}
max = prev1; temp = ;
prev1 = ;
prev2 = ;
for( i=; i<=numsSize-; i++ )
{
temp = prev1;
prev1 = (prev2+nums[i])>prev1 ? (prev2+nums[i]) : prev1;
prev2 = temp;
}
max = max>prev1 ? max : prev1; return max;
} int main()
{
int nums[] = { ,,,,,, };
int numsSize = ; int ret = rob( nums, numsSize );
printf("%d\n", ret);
return ;
}