From 7d7a050d2390a43101730a65dd8fad93e69b99c4 Mon Sep 17 00:00:00 2001 From: keineahnung2345 Date: Wed, 21 Oct 2020 10:45:44 +0800 Subject: [PATCH] 1D DP --- 1626. Best Team With No Conflicts.cpp | 43 +++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/1626. Best Team With No Conflicts.cpp b/1626. Best Team With No Conflicts.cpp index 05df689..47e97d9 100644 --- a/1626. Best Team With No Conflicts.cpp +++ b/1626. Best Team With No Conflicts.cpp @@ -194,3 +194,46 @@ class Solution { return backtrack(scores, ages, players, 0, -1, 0); } }; + +//1D DP +//each cell means the optimal can be got using the previous i players +//https://leetcode.com/problems/best-team-with-no-conflicts/discuss/899475/Fairly-easy-DP +//Runtime: 232 ms, faster than 51.78% of C++ online submissions for Best Team With No Conflicts. +//Memory Usage: 19.2 MB, less than 5.33% of C++ online submissions for Best Team With No Conflicts. +class Solution { +public: + int bestTeamScore(vector& scores, vector& ages) { + int n = scores.size(); + + vector players(n); + iota(players.begin(), players.end(), 0); + + //sort + sort(players.begin(), players.end(), + [&](int& p1, int& p2){ + return (ages[p1] == ages[p2]) ? (scores[p1] < scores[p2]) : (ages[p1] < ages[p2]); + }); + + vector dp(n); + //the actual index + int pi, pj; + + //visit the players, the younger the earlier to be visited + for(int i = 0; i < n; ++i){ + //map to the actual index + pi = players[i]; + dp[i] = scores[pi]; + + //visit players younger than pi + for(int j = 0; j < i; ++j){ + pj = players[j]; + if(scores[pj] <= scores[pi]){ + //dp[i]: the optimal score can be got formed of players of younger than or equal to pi + dp[i] = max(dp[i], dp[j]+scores[pi]); + } + } + } + + return *max_element(dp.begin(), dp.end()); + } +};