题目:
代码(首刷看解析 2024年2月29日):
class Solution {
public:int robRange(vector<int>& nums, int start, int end) {if (start == end) return nums[start];vector<int> dp(nums.size(), 0); // 遍历dp[start] = nums[start];dp[start + 1] = max(nums[start], nums[start + 1]);for (int i = 2 + start; i <= end; ++i) {dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]);}return dp[end];}// 动态规划int rob(vector<int>& nums) {// 条件int n = nums.size();if (n == 0) return 0;if (n == 1) return nums[0];int res1 = robRange(nums, 0, n - 2);int res2 = robRange(nums, 1, n - 1);return max(res1, res2);}
};