首页 > 学院 > 开发设计 > 正文

213. House Robber II

2019-11-08 02:08:38
字体:
来源:转载
供稿:网友

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.

public class Solution { public int rob(int[] nums) { if (nums == null || nums.length == 0) return 0; if (nums.length == 1) return nums[0]; return Math.max(helper(nums, 0, nums.length-2), helper(nums, 1, nums.length-1)); } public int helper(int[] nums, int low, int high) { int include = 0, exclude = 0; for (int i = low; i <= high; i++) { int in = include, ex = exclude; include = ex + nums[i]; exclude = Math.max(in, ex); } return Math.max(include, exclude); }}class Solution {public: int rob(vector<int>& nums) { if (nums.empty() || nums.size() == 0) return 0; if (nums.size() == 1) return nums[0]; return max(helper(nums, 0, nums.size()-2), helper(nums, 1, nums.size()-1)); } int helper(vector<int>& nums, int low, int high) { int include = 0, exclude = 0; for (int i = low; i <= high; i++) { int in = include, ex = exclude; include = ex + nums[i]; exclude = max(in, ex); } return max(include, exclude); }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表