|
| 1 | +/* |
| 2 | + The Masseuse: |
| 3 | + A popular masseuse receives a sequence of back-to-back appointment requests and is debating |
| 4 | + which ones to accept. She needs a 15-minute break between appointments and therefore she cannot |
| 5 | + accept any adjacent requests. Given a sequence of back-to-back appointment requests (all multiples |
| 6 | + of 15 minutes, none overlap, and none can be moved), find the optimal (highest total booked minutes) |
| 7 | + set the masseuse can honor. Return the number of minutes. |
| 8 | +
|
| 9 | + EXAMPLE |
| 10 | + Input: {30, 15, 60, 75, 45, 15, 15, 45} |
| 11 | + Output: 180 minutes ({30, 60, 45, 45}) |
| 12 | +
|
| 13 | + INPUT: {75, 105, 120, 75, 90, 135} |
| 14 | + OUTPUT: 330 minutes ({75, 120, 135}) |
| 15 | + */ |
| 16 | + |
| 17 | +// g++ 16-The-Masseuse.cpp --std=c++11 |
| 18 | + |
| 19 | +#include <iostream> |
| 20 | +#include <vector> |
| 21 | + |
| 22 | +using std::cout; |
| 23 | +using std::endl; |
| 24 | +using std::vector; |
| 25 | + |
| 26 | +int optimalBooking( const vector<int> input ) { |
| 27 | + int maxBooking=0; |
| 28 | + vector< int > max( input.size(), 0 ); |
| 29 | + max[0] = input[0]; |
| 30 | + max[1] = input[0] > input[1] ? input[0] : input[1]; |
| 31 | + for( int i = 2; i < input.size(); i++ ) { |
| 32 | + if( max[i-2] + input[i] > max[ i-1 ] ) { |
| 33 | + max[ i ] = max[i-2] + input[i]; |
| 34 | + } else { |
| 35 | + max[i] = max[i-1]; |
| 36 | + } |
| 37 | + if( max[i] > maxBooking ) { |
| 38 | + maxBooking = max[i]; |
| 39 | + } |
| 40 | + } |
| 41 | + return maxBooking; |
| 42 | +} |
| 43 | + |
| 44 | +int optimalBookingV2( const vector<int> input ) { |
| 45 | + int maxBooking=0; |
| 46 | + int max; |
| 47 | + int maxTwoAway = input[0]; |
| 48 | + int maxOneAway = input[0] > input[1] ? input[0] : input[1]; |
| 49 | + for( int i = 2; i < input.size(); i++ ) { |
| 50 | + if( maxTwoAway + input[i] > maxOneAway ) { |
| 51 | + max = maxTwoAway + input[i]; |
| 52 | + } else { |
| 53 | + max = maxOneAway; |
| 54 | + } |
| 55 | + maxTwoAway = maxOneAway; |
| 56 | + maxOneAway = max; |
| 57 | + |
| 58 | + if( max > maxBooking ) { |
| 59 | + maxBooking = max; |
| 60 | + } |
| 61 | + } |
| 62 | + return maxBooking; |
| 63 | +} |
| 64 | + |
| 65 | +int main() { |
| 66 | + vector<int> input1 = {30, 15, 60, 75, 45, 15, 15, 45}; |
| 67 | + vector<int> input2 = {75, 105, 120, 75, 90, 135}; |
| 68 | + cout<< optimalBooking( input1 ) << endl; |
| 69 | + cout<< optimalBooking( input2 ) << endl; |
| 70 | + cout<< optimalBookingV2( input1 ) << endl; |
| 71 | + cout<< optimalBookingV2( input2 ) << endl; |
| 72 | + return 0; |
| 73 | +} |
0 commit comments