Skip to content

Commit 861d46c

Browse files
authored
Create 04 - Space Optimized - 1 | DP | Approach.cpp
1 parent d0f7a0e commit 861d46c

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class Solution {
2+
public:
3+
// Function to calculate the maximum "like-time coefficient"
4+
// satisfaction: vector containing satisfaction values of dishes
5+
int solve(vector<int>& satisfaction) {
6+
int n = satisfaction.size();
7+
8+
// Create two 1D DP arrays to store results of the current and next iterations
9+
// We use two arrays instead of a 2D table to optimize space
10+
vector<int> curr(n + 1, 0); // Current state
11+
vector<int> next(n + 1, 0); // Next state
12+
13+
// Iterate over the satisfaction array in reverse order
14+
// satis represents the current index in the satisfaction array
15+
for (int satis = n - 1; satis >= 0; satis--) {
16+
// Iterate over possible time multipliers in reverse order
17+
for (int time = satis; time >= 0; time--) {
18+
// Option 1: Include the current dish
19+
// Add its contribution to the result, and increment the time multiplier
20+
int include = satisfaction[satis] * (time + 1) + next[time + 1];
21+
22+
// Option 2: Exclude the current dish
23+
// Skip the current dish, keeping the same time multiplier
24+
int exclude = 0 + next[time];
25+
26+
// Store the maximum of the two options in the current DP array
27+
curr[time] = max(include, exclude);
28+
}
29+
30+
// Move the current state to the next state for the next iteration
31+
next = curr;
32+
}
33+
34+
// Return the maximum value starting from index 0 with time multiplier 1
35+
return curr[0];
36+
}
37+
38+
// Main function to calculate the maximum "like-time coefficient"
39+
int maxSatisfaction(vector<int>& satisfaction) {
40+
// Step 1: Sort the satisfaction array in ascending order
41+
// Sorting ensures that we process less satisfying dishes first
42+
sort(satisfaction.begin(), satisfaction.end());
43+
44+
// Step 2: Use the solve function to compute the result
45+
return solve(satisfaction);
46+
}
47+
};

0 commit comments

Comments
 (0)