您的位置:首页 > 其它

LeetCode 213

2016-05-11 17:43 288 查看
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 == 0 )
{
return 0;
}
if( numsSize == 1 )
{
return nums[0];
}

int max = 0;
int prev1 = 0;
int prev2 = 0;

int i, temp;

temp  = 0;
prev1 = 0;
prev2 = 0;
for( i=0; i<=numsSize-2; i++ )
{
temp = prev1;
prev1 = (prev2+nums[i])>prev1 ? (prev2+nums[i]) : prev1;
prev2 = temp;
}
max = prev1;

temp  = 0;
prev1 = 0;
prev2 = 0;
for( i=1; i<=numsSize-1; 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[] = { 2,1,1,4,7,3,0 };
int numsSize = 7;

int ret = rob( nums, numsSize );
printf("%d\n", ret);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: