[caption - dynamic programming - interview] masseuse – leetcode

Time:2021-3-6

Title: masseuse

 

A famous masseuse will receive a steady stream of appointment requests, each appointment can choose to accept or not. There is a break between each appointment, so she can’t accept adjacent appointments. Given an appointment request sequence, find the optimal appointment set for the masseuse (the total appointment time is the longest), and return the total number of minutes.

Note: this question is slightly changed from the original one

 

Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: choose No.1 appointment and No.3 appointment, total duration = 1 + 3 = 4.
Example 2:

Input: [2,7,9,3,1]
Output: 12
Explanation: choose No.1 appointment, No.3 appointment and No.5 appointment, the total duration = 2 + 9 + 1 = 12.
Example 3:

Input: [2,1,4,5,3,1,1,3]
Output: 12
Explanation: select No.1 appointment, No.3 appointment, No.5 appointment and No.8 appointment, the total duration = 2 + 4 + 3 + 3 = 12.


Dynamic programming problem:

Set the DP [i] array to indicate the maximum appointment time when considering the i-th appointment.

The state transfer equation is obtaineddp[i] = max{ dp[i-1], dp[i-2]+nums[i] };

Code (c) above:

int max( int a, int b ) { return a>b?a:b; }

int massage(int* nums, int numsSize){

    if( numsSize == 0 ) return 0;
    if( numsSize == 1 ) return nums[0];

    int dp[numsSize];
    dp[0] = nums[0];
    dp[1] = max( nums[0], nums[1] );

    for( int i = 2; i < numsSize; i++ ) {
        dp[i] = max( dp[i-1], dp[i-2]+nums[i] );
    }

    return dp[numsSize-1];
}

2020-03-24-11:12:57