leetcode 213 : House Robber II,leetcoderobber

來源:互聯網
上載者:User

leetcode 213 : House Robber II,leetcoderobber
House Robber IITotal Accepted: 654 Total Submissions: 2631

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 arearranged 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 tonightwithout alerting the police.

[思路]

House Robber I的升級版. 因為第一個element 和最後一個element不能同時出現. 則分兩次call House Robber I. case 1: 不包括最後一個element. case 2: 不包括第一個element.

兩者的最大值即為全域最大值

[CODE]

public class Solution {    //1 2 3    public int rob(int[] nums) {        if(nums==null || nums.length==0) return 0;        if(nums.length==1) return nums[0];        if(nums.length==2) return Math.max(nums[0], nums[1]);        return Math.max(robsub(nums, 0, nums.length-2), robsub(nums, 1, nums.length-1));    }        private int robsub(int[] nums, int s, int e) {        int n = e - s + 1;        int[] d =new int[n];        d[0] = nums[s];        d[1] = Math.max(nums[s], nums[s+1]);                for(int i=2; i<n; i++) {            d[i] = Math.max(d[i-2]+nums[s+i], d[i-1]);        }        return d[n-1];    }}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.