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

xxxqqq

  • 博客园
  • 联系
  • 订阅
  • 管理

View Post

House Robber II

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.

Notice This is an extension of House Robber.

Example

nums = [3,6,4], return 6

这题的做法是run两遍House Robber的算法 一遍包含第一个house不包含最后一个 二遍包含最后一个房子不包含第一个房子

实际上cover了三种case:1 含第一个不含最后一个 2 含最后一个不含第一个 3 两个全不包含

 

复制代码
 1 public class Solution {
 2     /**
 3      * @param nums: An array of non-negative integers.
 4      * return: The maximum amount of money you can rob tonight
 5      */
 6     public int houseRobber2(int[] nums) {
 7         // write your code here
 8         if(nums==null||nums.length==0){
 9             return 0;
10         }
11         if(nums.length==1) return nums[0];
12         
13         return Math.max(helper(nums, 0, nums.length-2), helper(nums, 1, nums.length-1));
14     }
15     private int helper(int[] nums, int start, int end){
16         int f1 = 0;
17         int f2 = 0;
18         
19         for(int i=start; i<=end; i++){
20             int temp1 = f1;
21             f1=Math.max(f1, f2+nums[i]);
22             f2=temp1;
23         }
24         return f1;
25     }
26 }
复制代码

posted on 2017-05-10 13:16  xxxqqq  阅读(246)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3