• LeetCode 213: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.

    Credits:
    Special thanks to @Freezen for adding this problem and creating all test cases.

    //和上一题相似,仅仅是多了一个“环”的条件,就是抢了第一家,就不能抢最后一家
    //分别计算抢第二家到最后一家与抢第一家到倒数第二家的最大值,取两个值中更大的那个就是结果。
    class Solution {
    public:
    	int rob(vector<int>& nums) {
    		int n = nums.size();
    		if (n == 0) return 0;
    		if (n == 1) return nums[0];
    
    		int* dp = new int[n + 1];
    		//抢第一家到倒数第二家得到的金钱最大值
    		dp[0] = nums[0];  
    		for (int i = 1; i < n-1 ; ++i){
    			dp[i] = max(dp[i - 1],  (i==1? 0: dp[i-2])+nums[i] );
    		}
    		int res1=dp[n-2];
    
    		//抢第二家到最后一家得到的金钱最大值
    		dp[1] = nums[1];
    		for (int i = 2; i < n ; ++i){
    			dp[i] = max(dp[i - 1], (i == 2 ? 0 : dp[i - 2]) + nums[i]);
    		}
    		int res2 = dp[n-1 ];
    
    		return max(res1, res2);//返回二者的较大值
    	}
    };
    


  • 相关阅读:
    unix中的rm,rmdir的使用
    jQuery的学习笔记4
    jQuery的学习笔记2
    outlook 2016 for windows 每次刷新发送接收邮件会弹出登陆界面
    Azure SQL Data Warehouse
    Hadoop---Google MapReduce(转)
    Java 1.8特性
    SQL——Mysql数据库介绍
    接口和简单工厂设计模式
    自定义异常
  • 原文地址:https://www.cnblogs.com/cxchanpin/p/7027804.html
Copyright © 2020-2023  润新知