You are given a binary string s and a positive integer k.
Return the length of the longest subsequence ofsthat makes up a binary number less than or equal tok.
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.
Input:
s ="1001010", k =5Output:
5Explanation: The longest subsequence of s that makes up a binary number less than or equal to 5is"00010", as this number is equal to 2in decimal.Note that "00100" and "00101" are also possible, which are equal to 4 and 5in decimal, respectively.The length of this subsequence is5, so 5is returned.
Example 2:
1
2
3
4
5
6
Input:
s ="00101001", k =1Output:
6Explanation: "000001"is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1in decimal.The length of this subsequence is6, so 6is returned.
To maximize the length of the subsequence, we want to include as many ‘0’s as possible (since leading zeros don’t increase the value), and then greedily include ‘1’s from the right (least significant bits) as long as the resulting binary value does not exceed k.
classSolution {
public:int longestSubsequence(string s, int k) {
int n = s.size(), ans =0, zeros =0;
for (char c : s) if (c =='0') zeros++;
longlong val =0, pow2 =1;
int ones =0;
for (int i = n -1; i >=0; --i) {
if (s[i] =='1') {
if (val + pow2 <= k) {
val += pow2;
ones++;
}
}
if (pow2 > k) break;
pow2 <<=1;
}
return zeros + ones;
}
};
classSolution {
publicintlongestSubsequence(String s, int k) {
int n = s.length(), zeros = 0, ones = 0;
for (char c : s.toCharArray()) if (c =='0') zeros++;
long val = 0, pow2 = 1;
for (int i = n - 1; i >= 0; --i) {
if (s.charAt(i) =='1') {
if (val + pow2 <= k) {
val += pow2;
ones++;
}
}
if (pow2 > k) break;
pow2 <<= 1;
}
return zeros + ones;
}
}