您的位置:首页 > 其它

LeetCode 198

2016-05-11 17:42 423 查看
House Robber

You are a professional robber planning to rob houses along a street.
Each house has a certain amount of money stashed,
the only constraint stopping you from robbing each of them
is that adjacent houses have security system connected
and it will automatically contact the police
if two adjacent houses were broken into on the same night.

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: LeetCode198.c
> Author: Juntaran
> Mail: JuntaranMail@gmail.com
> Created Time: Wed 11 May 2016 15:24:30 PM CST
************************************************************************/

/*************************************************************************

House Robber

You are a professional robber planning to rob houses along a street.
Each house has a certain amount of money stashed,
the only constraint stopping you from robbing each of them
is that adjacent houses have security system connected
and it will automatically contact the police
if two adjacent houses were broken into on the same night.

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>

/* 改变了原数组的值 */
int rob( int* nums, int numsSize )
{
if( numsSize == 0 )
{
return 0;
}
if( numsSize == 1 )
{
return nums[0];
}

nums[1] = nums[0]>nums[1] ? nums[0] : nums[1];

int i;
for( i=2; i<=numsSize-1; i++ )
{
nums[i] = (nums[i-2]+nums[i])>nums[i-1] ? (nums[i-2]+nums[i]) : nums[i-1];
}
return nums[numsSize-1];
}

/* 两个变量共同维护 */
int rob2( int* nums, int numsSize )
{
if( numsSize == 0 )
{
return 0;
}
if( numsSize == 1 )
{
return nums[0];
}

int prev1 = 0;
int prev2 = 0;

int i, temp;
for( i=0; i<=numsSize-1; i++ )
{
temp = prev1;
prev1 = (prev2+nums[i])>prev1 ? (prev2+nums[i]) : prev1;
prev2 = temp;
}
return prev1;
}

int main()
{
int nums[] = { 2,1,1,4,0 };
int numsSize = 5;

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