Skip to content

Commit caf82ad

Browse files
authored
Create 01 - Recursive Approach (caused TLE).cpp
1 parent 88fcff4 commit caf82ad

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public:
3+
// Recursive function to solve the problem
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+
int solve(vector<int>& satisfaction, int index, int time) {
8+
int n = satisfaction.size();
9+
10+
// Base case: if we've processed all dishes, return 0
11+
if (index == n) return 0;
12+
13+
// Option 1: Include the current dish
14+
// Add the "like-time coefficient" for the current dish and move to the next dish
15+
int include = satisfaction[index] * time + solve(satisfaction, index + 1, time + 1);
16+
17+
// Option 2: Exclude the current dish
18+
// Skip the current dish and keep the same time multiplier
19+
int exclude = 0 + solve(satisfaction, index + 1, time);
20+
21+
// Return the maximum of the two options
22+
return max(include, exclude);
23+
}
24+
25+
// Main function to calculate the maximum "like-time coefficient"
26+
int maxSatisfaction(vector<int>& satisfaction) {
27+
// Step 1: Sort the satisfaction array in ascending order
28+
// This ensures we process the least satisfying dishes first, enabling us to skip them if needed
29+
sort(satisfaction.begin(), satisfaction.end());
30+
31+
// Step 2: Call the recursive function starting with index 0 and time 1
32+
return solve(satisfaction, 0, 1);
33+
}
34+
};

0 commit comments

Comments
 (0)