Java for LeetCode 213 House Robber II

來源:互聯網
上載者:User

標籤:

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.

解題思路:

可以分解為兩種情況:包含nums[0]和不包含nums[0],分別求解算出最大即可,JAVA實現如下;

    public int rob(int[] nums) {if (nums == null || nums.length == 0)return 0;else if (nums.length <= 2)return Math.max(nums[0], nums[nums.length - 1]);else if(nums.length==3)return Math.max(nums[0], Math.max(nums[1],nums[2]));int res = 0;int[] dp = new int[nums.length];dp[0] = nums[0];dp[2] = nums[0] + nums[2];dp[3] = nums[0] + nums[3];for (int i = 4; i < nums.length-1; i++)dp[i] = nums[i] + Math.max(dp[i - 2], dp[i - 3]);res=Math.max(dp[nums.length-2],dp[nums.length-3]);dp[1] = nums[1];dp[2] = nums[2];dp[3] = nums[3] + nums[1];for (int i = 4; i < nums.length; i++)dp[i] = nums[i] + Math.max(dp[i - 2], dp[i - 3]);return Math.max(res, Math.max(dp[nums.length-1],dp[nums.length-2]));    }

 

Java for LeetCode 213 House Robber II

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.