Problem Description
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
.
Key Insights
- A subsequence can include leading zeros.
- The empty string is treated as equal to 0.
- The solution needs to derive a valid binary number from the string
s
such that its decimal value does not exceedk
. - The approach involves checking how many zeros can be included and how many ones can be included without exceeding the given value of
k
.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
To solve the problem, we can iterate through the binary string s
and count the number of 0
s and 1
s. The binary number represented by the longest subsequence can have all the 0
s and a limited number of 1
s based on the value of k
. We need to check if including a 1
keeps the binary number less than or equal to k
. This can be done by maintaining a count of the decimal value of the formed binary number and comparing it with k
.