LEETCODE || face questions 17.16. Masseur

The face questions 17.16 masseur
Title:
a well-known massage therapist will receive a steady stream of the reservation request, the reservation can be selected for each connection or not connected. Between each reservation service have time to rest, so she could not accept neighboring appointment. Given a sequence of reservation request, the reservation for the massage therapist to find the optimal set (longest total reservation), and returns the total number of minutes.

Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: selecting a reservation number and reservation number 3, total length = 3 + 1 = 4.

Example 2:

Input: [2,7,9,3,1]
Output: 12
Explanation: selecting a reservation number, No. 3 and No. 5 reservation booking, total length = 2 + 9 + 1 = 12.

Example 3:

Input: [2,1,4,5,3,1,1,3]
Output: 12
Explanation: 1 selection number reservation, reservation No. 3, No. 5 and No. 8 reservation booking, total length = 2 + 3 + 4 + 3 = 12.

This problem can solve problems using the idea of ​​dynamic programming.

First, we use the 1 and 0 if this took reservation, took 1 represents the current reservation, then 0 indicates no current reservation; with DP [i] [0] indicates the i-th access is not reserved, DP [i] [ 1] indicates the i-th access reservation.

Subject requires us to find the optimal set of appointments, assume that the current is the i-th appointment, the current maximum length of reservation can be considered from two aspects, first i took an appointment or do not take the i-th reservation, took over when the i-th when a length of reservation, as subject of the request can not accept reservation adjacent, so the first i-1 th reservation must not contact, then the i-th reservation took a total reservation dp [i] [1] = dp [i -1] [0] + when num [i], then the i-th reservation without maximum total reservation value dp [i] [1] = max (dp [i-1] [0], dp [i- 1] [1]).

We can see, each fact, when using i-1 of the total reservation length is calculated when the reservation is the i-th long, so we can use the two variables dp1 and dp0 to record each reservation sum, and then calculates the next time reservation length . code show as below:

class Solution {
public:
    int massage(vector<int>& nums) {
        if (nums.size() == 0)
            return 0;
        int dp0 = 0, dp1 = nums[0];
        for (int i = 1; i < nums.size(); ++i){
            int tdp0 = max(dp0, dp1);
            int tdp1 = dp0 + nums[i];
            dp0 = tdp0;
            dp1 = tdp1;
        }
        return max(dp0, dp1);
    }
};
Published an original article · won praise 0 · Views 46

Guess you like

Origin blog.csdn.net/qq_41809369/article/details/105082752