Leetcode: House Robber
2015-08-05 22:00
399 查看
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.
比较简单的DP题。不能同时取相邻的房子,那么到当前房子最大的值取决于它前3,前2的房子值,从中选择大的即可。
class Solution {
public:
int rob(vector<int>& nums) {
int max1 = 0;
int max2 = 0;
int max3 = 0;
for (int i = 0; i < nums.size(); ++i) {
int curMax = max(max1, max2) + nums[i];
max1 = max2;
max2 = max3;
max3 = curMax;
}
return max(max2, max3);
}
};
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.
比较简单的DP题。不能同时取相邻的房子,那么到当前房子最大的值取决于它前3,前2的房子值,从中选择大的即可。
class Solution {
public:
int rob(vector<int>& nums) {
int max1 = 0;
int max2 = 0;
int max3 = 0;
for (int i = 0; i < nums.size(); ++i) {
int curMax = max(max1, max2) + nums[i];
max1 = max2;
max2 = max3;
max3 = curMax;
}
return max(max2, max3);
}
};
相关文章推荐
- 基于Android中dp和px之间进行转换的实现代码
- Android中dip、dp、sp、pt和px的区别详解
- LFC1.0.0 版本发布
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- Android px、dp、sp之间相互转换
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- android中像素单位dp、px、pt、sp的比较
- LeetCode[Day 1] Two Sum 题解