Skip to content

Commit 9b333e0

Browse files
authored
Create 05 - Space Optimized - 2 | DP | Approach.cpp
1 parent 861d46c commit 9b333e0

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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+
// Variables to keep track of the results
9+
int maxSatisfaction = 0; // Maximum satisfaction achieved so far
10+
int cumulativeSum = 0; // Running sum of satisfaction values
11+
int runningTotal = 0; // Current "like-time coefficient"
12+
13+
// Traverse the satisfaction array in reverse order
14+
// This ensures we consider the most satisfying dishes last
15+
for (int i = n - 1; i >= 0; i--) {
16+
cumulativeSum += satisfaction[i]; // Add current satisfaction value to the cumulative sum
17+
runningTotal += cumulativeSum; // Update the running total with the new cumulative sum
18+
19+
// Update the maximum satisfaction if the current running total is greater
20+
if (runningTotal > maxSatisfaction)
21+
maxSatisfaction = runningTotal;
22+
else
23+
break; // Stop processing if adding more dishes reduces the total
24+
}
25+
26+
// Return the maximum satisfaction found
27+
return maxSatisfaction;
28+
}
29+
30+
// Main function to calculate the maximum "like-time coefficient"
31+
int maxSatisfaction(vector<int>& satisfaction) {
32+
// Step 1: Sort the satisfaction array in ascending order
33+
// Sorting ensures we can efficiently process from least to most satisfying
34+
sort(satisfaction.begin(), satisfaction.end());
35+
36+
// Step 2: Use the solve function to compute the result
37+
return solve(satisfaction);
38+
}
39+
};

0 commit comments

Comments
 (0)