https://leetcode.com/problems/delete-and-earn/description/
int deleteAndEarn(vector<int>& nums) {
vector<int> ns(100001, 0);
for(int i: nums) ns[i]++;
int skip = 0, keep = 0;
for(int i=1; i<ns.size(); i++) {
int keepi = skip + i * ns[i];
skip = max(keep, skip);
keep = keepi;
}
return max(keep, skip);
}
Friday, January 5, 2018
Thursday, January 4, 2018
516. Longest Palindromic Subsequence
https://leetcode.com/problems/longest-palindromic-subsequence/description/
int longestPalindromeSubseq(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int> (n, 0));
for(int j=0; j<n; j++) {
dp[j][j] = 1;
for(int i=j-1; i>=0; i--) {
if(s[i] == s[j]) dp[i][j] = dp[i+1][j-1] + 2;
else dp[i][j] = max(dp[i+1][j], dp[i][j-1]);
}
}
return dp[0][n-1];
}
int longestPalindromeSubseq(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int> (n, 0));
for(int j=0; j<n; j++) {
dp[j][j] = 1;
for(int i=j-1; i>=0; i--) {
if(s[i] == s[j]) dp[i][j] = dp[i+1][j-1] + 2;
else dp[i][j] = max(dp[i+1][j], dp[i][j-1]);
}
}
return dp[0][n-1];
}
Subscribe to:
Posts (Atom)