diff --git a/1626. Best Team With No Conflicts.cpp b/1626. Best Team With No Conflicts.cpp index d5faa9a..05df689 100644 --- a/1626. Best Team With No Conflicts.cpp +++ b/1626. Best Team With No Conflicts.cpp @@ -147,3 +147,50 @@ class Solution { return max_score; } }; + +//a trial of using memorization, slower than previous? +//TLE +//44 / 147 test cases passed. +class Solution { +public: + vector>> memo; + + int backtrack(vector& scores, vector& ages, vector& players, int pi, int last_chosen, int cur_score){ + if(memo[pi+1][last_chosen+1].find(cur_score) != memo[pi+1][last_chosen+1].end()){ + return memo[pi+1][last_chosen+1][cur_score]; + }else if(pi == players.size()){ + return memo[pi+1][last_chosen+1][cur_score] = cur_score; + }else{ + int res = 0; + + //not choose cur + res = backtrack(scores, ages, players, pi+1, last_chosen, cur_score); + + int p = players[pi]; + + //don't need to check age! + if(last_chosen == -1 || + !(/*ages[p] > ages[chosen.back()] && */scores[p] < scores[last_chosen])){ + //choose cur + res = max(res, backtrack(scores, ages, players, pi+1, p, cur_score+scores[p])); + } + + return memo[pi+1][last_chosen+1][cur_score] = res; + } + } + + int bestTeamScore(vector& scores, vector& ages) { + int n = scores.size(); + vector players(n); + iota(players.begin(), players.end(), 0); + + sort(players.begin(), players.end(), [&](int& pi1, int& pi2){ + return (ages[pi1] == ages[pi2]) ? scores[pi1] < scores[pi2] : ages[pi1] < ages[pi2]; + }); + + memo = vector>>(n+2, + vector>(n+2)); + + return backtrack(scores, ages, players, 0, -1, 0); + } +};