[LeetCode] Longest Binary Subsequence Less Than or Equal to K

2311. Longest Binary Subsequence Less Than or Equal to K

You are given a binary string s and a positive integer k.

Return the length of the longest subsequence of s that makes up a binary number less than or equal to k.

Note:

  • The subsequence can contain leading zeroes.
  • The empty string is considered to be equal to 0.
  • A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int longestSubsequence(string s, int k) {
long long now = 0, m = 0, n = s.length(), res = 0;

for(int i = n - 1; i >= 0; i--,m++) {
if(s[i] == '0') res++;
else if(m <= 30) {
if(((1ll<<m) + now) <= k){
now += (1ll<<m);
res++;
}
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/19/PS/LeetCode/longest-binary-subsequence-less-than-or-equal-to-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.