-
Notifications
You must be signed in to change notification settings - Fork 231
Expand file tree
/
Copy pathReducingDishes.cpp
More file actions
83 lines (60 loc) · 2.48 KB
/
ReducingDishes.cpp
File metadata and controls
83 lines (60 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// https://leetcode.com/problems/reducing-dishes/description/
class Solution {
public:
// Simple Recursive Solution
// int solve(vector<int>& satisfaction, int index, int time){
// if(index==satisfaction.size())
// return 0;
// int include= satisfaction[index]*(time+1) + solve(satisfaction, index+1, time+1);
// int exclude= 0 + solve(satisfaction, index+1, time);
// return max(include, exclude);
// }
// Recursion + Memoization (Top-Down Approach)
// int solve(vector<int>& satisfaction, int index, int time, vector<vector<int>> &dp){
// if(index==satisfaction.size())
// return 0;
// if(dp[index][time]!=-1)
// return dp[index][time];
// int include= satisfaction[index]*(time+1) + solve(satisfaction, index+1, time+1, dp);
// int exclude= 0 + solve(satisfaction, index+1, time, dp);
// dp[index][time]= max(include, exclude);
// return dp[index][time];
// }
// Tabulation (Bottom-Up Approach)
// int solve(vector<int>& satisfaction){
// int n= satisfaction.size();
// vector<vector<int>> dp(n+1, vector<int> (n+1, 0));
// for(int index= n-1; index>=0; index--){
// for(int time= index; time>=0; time--){
// int include= satisfaction[index]*(time+1) + dp[index+1][time+1];
// int exclude= 0 + dp[index+1][time];
// dp[index][time]= max(include, exclude);
// }
// }
// return dp[0][0];
// }
int solve(vector<int>& satisfaction){
int n= satisfaction.size();
vector<int> curr(n+1, 0);
vector<int> next(n+1, 0);
for(int index= n-1; index>=0; index--){
for(int time= index; time>=0; time--){
int include= satisfaction[index]*(time+1) + next[time+1];
int exclude= 0 + next[time];
curr[time]= max(include, exclude);
}
next= curr;
}
return next[0];
}
int maxSatisfaction(vector<int>& satisfaction) {
sort(satisfaction.begin(), satisfaction.end());
// Simple Recursive Solution
// return solve(satisfaction, 0, 0);
// Recursion + Memoization
// int n= satisfaction.size();
// vector<vector<int>> dp(n+1, vector<int> (n+1, -1));
// return solve(satisfaction, 0, 0, dp);
return solve(satisfaction);
}
};