90. masseur
Topic Link
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/the-masseuse-lcci
Title Description
A 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.
Note: This problem is relatively minor changes to the original title
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.
Key Technology
Dynamic Programming
Topic analysis
- When nums is empty, return 0;
- Take nums [0] and the nums [1] a large value so determined starting from No. 1 or No. 2 appointment reservation;
- Order DP [i] storing the maximum position i and the sub-array;
- When a position adjacent to the reservation can not be reserved, so it should be determined whether the current element (nums [i]) + dp [i-2] is larger than dp [i-1], it is possible to write a state transition equation: dp [i] = math.max (dp [i-1], dp [i-2] + nums [i]);
/** * @param {number[]} nums * @return {number} */ var massage = function(nums) { let len = nums.length; if(len === 0 || nums == null) return 0; let dp = new Array(len).fill(0); dp[0] = nums[0]; dp[1] = Math.max(nums[0],nums[1]); for(let i=2;i<len;i++){ dp[i] = Math.max(dp[i-1],dp[i-2]+nums[i]); } return dp[len-1]; };