题解 | 打家劫舍(二)
打家劫舍(二)
https://www.nowcoder.com/practice/a5c127769dd74a63ada7bff37d9c5815
class Solution { public: int rob(vector<int>& nums) { int n = nums.size(); if (n == 1) return nums[0]; auto line = [&](int l, int r) -> int { int pre2 = 0, pre1 = 0; // pre2=dp[i-2], pre1=dp[i-1] for (int i = l; i <= r; ++i) { int cur = max(pre1, pre2 + nums[i]); pre2 = pre1; pre1 = cur; } return pre1; }; return max(line(0, n - 2), line(1, n - 1)); } };