|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Recursive function to calculate the maximum "like-time coefficient" |
| 4 | + // satisfaction: vector containing satisfaction values |
| 5 | + // index: current index in the satisfaction array |
| 6 | + // time: current time multiplier for calculating the "like-time coefficient" |
| 7 | + // dp: memoization table to store intermediate results |
| 8 | + int solve(vector<int>& satisfaction, int index, int time, vector<vector<int>>& dp) { |
| 9 | + int n = satisfaction.size(); |
| 10 | + |
| 11 | + // Base case: If all dishes have been considered, return 0 |
| 12 | + if (index == n) return 0; |
| 13 | + |
| 14 | + // Check if the result for this state is already computed |
| 15 | + if (dp[index][time] != -1) return dp[index][time]; |
| 16 | + |
| 17 | + // Option 1: Include the current dish in the calculation |
| 18 | + // Add its contribution and move to the next dish with incremented time |
| 19 | + int include = satisfaction[index] * time + solve(satisfaction, index + 1, time + 1, dp); |
| 20 | + |
| 21 | + // Option 2: Exclude the current dish from the calculation |
| 22 | + // Move to the next dish without incrementing the time |
| 23 | + int exclude = 0 + solve(satisfaction, index + 1, time, dp); |
| 24 | + |
| 25 | + // Store the maximum result in the memoization table |
| 26 | + dp[index][time] = max(include, exclude); |
| 27 | + |
| 28 | + // Return the result for the current state |
| 29 | + return dp[index][time]; |
| 30 | + } |
| 31 | + |
| 32 | + // Main function to calculate the maximum "like-time coefficient" |
| 33 | + int maxSatisfaction(vector<int>& satisfaction) { |
| 34 | + // Step 1: Sort the satisfaction array in ascending order |
| 35 | + // Sorting helps to efficiently decide whether to include or exclude |
| 36 | + sort(satisfaction.begin(), satisfaction.end()); |
| 37 | + |
| 38 | + int n = satisfaction.size(); |
| 39 | + |
| 40 | + // Step 2: Create a memoization table initialized to -1 |
| 41 | + // dp[i][j] represents the maximum "like-time coefficient" starting from index i with time j |
| 42 | + vector<vector<int>> dp(n + 1, vector<int>(n + 1, -1)); |
| 43 | + |
| 44 | + // Step 3: Call the recursive function starting with index 0 and time 1 |
| 45 | + return solve(satisfaction, 0, 1, dp); |
| 46 | + } |
| 47 | +}; |
0 commit comments