Skip to content

Commit

Permalink
[feat ]: leetcode 2370
Browse files Browse the repository at this point in the history
Signed-off-by: Bo-Wei Chen(BWbwchen) <[email protected]>
  • Loading branch information
BWbwchen committed Apr 28, 2024
1 parent a9f12b6 commit 74cc3bf
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions leetcode/2370_Longest-Ideal-Subsequence.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class Solution {
public:
inline bool valid(char a, char b, int k) {
return abs(a - b) <= k;
}
int longestIdealString(string s, int k) {
int n = s.size();
vector<int> dp(26, 0); // a ~ z

for (auto c : s) {
int tmp = std::numeric_limits<int>::min();
for (char j = 'a'; j <= 'z'; ++j) {
// dp[c] = max_j(dp[j]) + 1, where valid(j, c, k) == true
if (valid(j, c, k))
tmp = max(tmp, dp[j-'a']);
}
// Why use tmp? Because we can not update the dp[c-'a'] and compare it simultaneously.
dp[c-'a'] = max(dp[c-'a'], tmp + 1);
}
return *max_element(dp.begin(), dp.end());
}
};

0 comments on commit 74cc3bf

Please sign in to comment.