*************
C++
topic: 面试题 17.16. 按摩师 - 力扣(LeetCode)
*************
Inspect the topic first.
![]() |
And It just remainds me another topic, which is stocks problems.
买卖股票的最佳时机 - 合集-优快云博客![]() |
![]() |
By the way, do you know the king of massage?
![]() |
Topic like this is to define the states of the each day. In the day i, receive the appointment or reject the appointment. Define dp[i] is the maxmum work time.
for the i appointment, two choices, receive or reject.
- accepts the i-th appointment, but then she can't accept the i-1th appointment, because the total time is dp[i-2] + nums[i].
- doesn't accept the i-th appointment, then the total time is dp[i-1].
So the transfer equation is
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]).
int dp[0] = nums[1];
int dp[1] = max(nums[1], nums[2])
for ecample:
Suppose `nums = [1, 2, 3, 4, 5]`.
- `n = 5`
- `dp[0] = 1`
- `dp[1] = max(1, 2) = 2`
- `dp[2] = max(2, 1 + 3) = max(2, 4) = 4`
- `dp[3] = max(4, 2 + 4) = max(4, 6) = 6`
- `dp[4] = max(6, 4 + 5) = max(6, 9) = 9`
So the maximum profit is 9, which seems correct. She can take appointments 1 (1), 3 (3), and 5 (5), totaling 9.
class Solution {
public:
int massage(vector<int>& nums) {
// always initilize something here
int n = nums.size();
vector<int> dp(n, 0);
dp[0] = nums[1];
dp[1] = max(nums[1], nums[2]);
for (int i = 2; i < n; i++){
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]);
}
return dp[n];
}
};
The code looks beautiful and runs error.
![]() |
I forget about the boundary conditions.
if n = 0; return 0;
if n = 1; return nums[0];
class Solution {
public:
int massage(vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0;
if (n == 1) return nums[0];
vector<int> dp(n, 0);
dp[0] = nums[0];
dp[1] = max(nums[0], nums[1]);
for (int i = 2; i < n; i++) {
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]);
}
return dp[n - 1];
}
};