Rob

在LeetCode上刷到一道题 关于最大数量的题 题目如下:

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

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.

Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:

Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.

就是给定你一个数组 相邻两个元素不能同时取 求能从这个数组得到的最大值。
一开始我想的太复杂了 导致一直想不出 其实问题很简单:相邻两个元素不能同时取 那么我们可以用一个数组来记录当前合法可取的最大数量 碰到下一个元素时 取最大值 :它的前一个最大值和他前面两个最大值和当前这个元素相加的和。(有点混乱了 看代码就能懂 :))

代码如下:

public static int rob(int[] nums) {
	     int[] n = new int[nums.length+1];//用数组n来记录n位元素的最大值.
	     for(int i=1;i<=nums.length;i++){
	    	 if(i == 1){
	    		 n[i] = nums[i-1];
	    		 continue;
	    	 }
	    	 n[i] = Math.max(n[i-1], n[i-2] + nums[i-1]);//核心  理解一哈 不难的.
	     }
		 return n[nums.length];
	 }
发布了19 篇原创文章 · 获赞 0 · 访问量 297

猜你喜欢

转载自blog.csdn.net/XXuan_/article/details/99556700
Rob
job
BOB
LOB
ob