Skip to content

Commit

Permalink
1D DP
Browse files Browse the repository at this point in the history
  • Loading branch information
keineahnung2345 authored Oct 21, 2020
1 parent 138ae7e commit 7d7a050
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions 1626. Best Team With No Conflicts.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<int>& scores, vector<int>& ages) {
int n = scores.size();

vector<int> 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<int> 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());
}
};

0 comments on commit 7d7a050

Please sign in to comment.