zoukankan      html  css  js  c++  java
• # 198. House Robber

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.

Solution: use the idea of dynamic programming. use dp[i] to represent the max sum of non-adjacent numbers till i. the formula is dp[i]=max(dp[i-2]+nums[i],dp[i-1]), the initial is dp[0]=nums[0],dp[1]=max(nums[0],nums[1]). Here we only need dp[i-2] and dp[i-1] to get dp[i], so we can use two variants dp_pre2 and dp_pre1 to replace the dp array.

``` 1 class Solution {
2 public:
3     int rob(vector<int>& nums) {
4         int size=nums.size();
5         if (size==0) return 0;
6         if (size==1) return nums[0];
7         int dp_pre2=nums[0];
8         int dp_pre1=max(nums[0],nums[1]);
9         for (int i=2;i<size;i++){
10             int temp=max(dp_pre2+nums[i],dp_pre1);
11             dp_pre2=dp_pre1;
12             dp_pre1=temp;
13         }
14         return dp_pre1;
15     }
16 };```

])

• 相关阅读:
Linux_DNS服务器
Linux_DNS服务器
Linux_FTP服务器
Linux_FTP服务器
Linux_DHCP&DHCP Relay
分布式内存存储式元数据服务的构建
如何提高分布式系统的可观察性：Insight Tool的引入
论分布式系统中Metric框架的设计
分布式存储系统关于GDPR条例中的数据清除原则
Pipeline并行处理模型
• 原文地址：https://www.cnblogs.com/anghostcici/p/6911159.html