• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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.

Analysis: 

if the last one is not robbed, then you are free to choose whether to rob the first one. you can break the circle by assuming the first house is not robbed.

For example, 1 -> 2 -> 3 -> 1 becomes 2 -> 3 if 1 is not robbed.

Since every house is either robbed or not robbed and at least half of the houses are not robbed, the solution is simply the larger of two cases with consecutive houses, i.e. house i not robbed, break the circle, solve it, or house i + 1 not robbed. Hence, the following solution. I chose i = n and i + 1 = 0 for simpler coding. But, you can choose whichever two consecutive ones.

 1 class Solution {
 2     public int rob(int[] nums) {
 3         if (nums == null || nums.length == 0) return 0;
 4         if (nums.length == 1) return nums[0];
 5         return Math.max(helper(nums, 0, nums.length - 2), helper(nums, 1, nums.length - 1));
 6     }
 7     
 8     public int helper(int[] nums, int lo, int hi) {
 9         int prev2 = 0;
10         int prev1 = nums[lo];
11         for (int i = lo + 1; i <= hi; i++) {
12             int temp = prev1;
13             prev1 = Math.max(prev1, prev2 + nums[i]);
14             prev2 = temp;
15         }
16         return prev1;
17     }
18 }

 

posted @ 2015-12-17 12:20  neverlandly  阅读(339)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3