Ctrl K

Binary Number Under a Cap

Medium
You are given a string bits made of 0 and 1 and a non-negative integer cap. Cross out some characters (the rest keep their order) so that the remaining string, read as a binary number, is at most cap. Leading zeros are allowed, and an empty string counts as 0. Return the greatest possible length of the remaining string.
Example 1
bits="0110101", cap=6 → 5

For example, "00101" is 5, which does not exceed 6. Six characters are impossible: they would keep at least three ones, and the number would exceed 6.

Example 2
bits="111", cap=2 → 1

The possible subsequences are "1", "11" and "111", that is 1, 3 and 7. Only "1" fits.

Example 3
bits="1000", cap=1 → 3

Take the three zeros, which make 0. Keeping the leading one would give at least 4.

Constraints
  • 1 ≤ len(bits) ≤ 1000
  • bits contains only 0 and 1
  • 0 ≤ cap ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSplit Into Dictionary Words MediumEvery Bracketing Result MediumSteps Down to One MediumBrackets With Wildcards MediumBead String Without Twins Medium
loading Python…
Input
bits="0110101", cap=6
Expected
5

Run checks the first 3 tests in your browser. Submit checks all 101 tests on the server, hidden ones included.