|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Function to solve the problem using bottom-up dynamic programming |
| 4 | + // satisfaction: vector containing satisfaction values of dishes |
| 5 | + int solve(vector<int>& satisfaction) { |
| 6 | + int n = satisfaction.size(); |
| 7 | + |
| 8 | + // Create a DP table to store the maximum "like-time coefficient" values |
| 9 | + // dp[i][j] represents the maximum value achievable starting from index i with time j |
| 10 | + vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0)); |
| 11 | + |
| 12 | + // Iterate over the satisfaction array in reverse order |
| 13 | + // satis represents the current index in the satisfaction array |
| 14 | + for (int satis = n - 1; satis >= 0; satis--) { |
| 15 | + // Iterate over the possible time values in reverse order |
| 16 | + for (int time = satis; time >= 0; time--) { |
| 17 | + // Option 1: Include the current dish |
| 18 | + // Add its contribution to the result, and increment the time multiplier |
| 19 | + int include = satisfaction[satis] * (time + 1) + dp[satis + 1][time + 1]; |
| 20 | + |
| 21 | + // Option 2: Exclude the current dish |
| 22 | + // Skip the current dish, keeping the same time multiplier |
| 23 | + int exclude = 0 + dp[satis + 1][time]; |
| 24 | + |
| 25 | + // Store the maximum of the two options in the DP table |
| 26 | + dp[satis][time] = max(include, exclude); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + // Return the maximum value starting from index 0 with time multiplier 1 |
| 31 | + return dp[0][0]; |
| 32 | + } |
| 33 | + |
| 34 | + // Main function to calculate the maximum "like-time coefficient" |
| 35 | + int maxSatisfaction(vector<int>& satisfaction) { |
| 36 | + // Step 1: Sort the satisfaction array in ascending order |
| 37 | + // Sorting ensures we process less satisfying dishes first |
| 38 | + sort(satisfaction.begin(), satisfaction.end()); |
| 39 | + |
| 40 | + // Step 2: Use the solve function to compute the result |
| 41 | + return solve(satisfaction); |
| 42 | + } |
| 43 | +}; |
0 commit comments