Skip to content

Commit 9edbbef

Browse files
Update dynamic-programming.md
1 parent ff1448d commit 9edbbef

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

dynamic-programming.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -790,6 +790,45 @@ int candy(vector<int>& ratings)
790790
return sm;
791791
}
792792

793+
// Graph based approach, add a directed edge between two adjacent students if rating is higher.
794+
// Then simply run a topological sort to get the candy count.
795+
int candy(vector<int>& ratings) {
796+
int n = ratings.size();
797+
vector<int> adj[n];
798+
vector<int> inDeg(n, 0);
799+
for (int i = 1; i < n; ++i) {
800+
if (ratings[i-1] > ratings[i]) {
801+
adj[i].push_back(i-1);
802+
inDeg[i-1]++;
803+
}
804+
if (ratings[i-1] < ratings[i]) {
805+
adj[i-1].push_back(i);
806+
inDeg[i]++;
807+
}
808+
}
809+
810+
int res = 0;
811+
queue<int> q;
812+
for (int i = 0; i < n; ++i) {
813+
if (inDeg[i] == 0) q.push(i);
814+
}
815+
int candy = 1;
816+
while (!q.empty())
817+
{
818+
int sz = q.size();
819+
while (sz--) {
820+
int u = q.front(); q.pop();
821+
res += candy;
822+
for (int &v : adj[u]) {
823+
inDeg[v]--;
824+
if (inDeg[v] == 0) q.push(v);
825+
}
826+
}
827+
candy++;
828+
}
829+
return res;
830+
}
831+
793832
/* One pass, constant space appraoch
794833
Observation: Candies are always given increment of 1. Local minimum number of
795834
candies given to a student is 1 so subdistribution is of form 1, 2, 3, ..., n or

0 commit comments

Comments
 (0)