Skip to content

Commit c58fa08

Browse files
committed
Sync LeetCode submission Runtime - 5 ms (39.84%), Memory - 17.9 MB (47.97%)
1 parent 9a8b94b commit c58fa08

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<p>You are given a binary string <code>s</code> and a positive integer <code>k</code>.</p>
2+
3+
<p>Return <em>the length of the <strong>longest</strong> subsequence of </em><code>s</code><em> that makes up a <strong>binary</strong> number less than or equal to</em> <code>k</code>.</p>
4+
5+
<p>Note:</p>
6+
7+
<ul>
8+
<li>The subsequence can contain <strong>leading zeroes</strong>.</li>
9+
<li>The empty string is considered to be equal to <code>0</code>.</li>
10+
<li>A <strong>subsequence</strong> is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.</li>
11+
</ul>
12+
13+
<p>&nbsp;</p>
14+
<p><strong class="example">Example 1:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> s = &quot;1001010&quot;, k = 5
18+
<strong>Output:</strong> 5
19+
<strong>Explanation:</strong> The longest subsequence of s that makes up a binary number less than or equal to 5 is &quot;00010&quot;, as this number is equal to 2 in decimal.
20+
Note that &quot;00100&quot; and &quot;00101&quot; are also possible, which are equal to 4 and 5 in decimal, respectively.
21+
The length of this subsequence is 5, so 5 is returned.
22+
</pre>
23+
24+
<p><strong class="example">Example 2:</strong></p>
25+
26+
<pre>
27+
<strong>Input:</strong> s = &quot;00101001&quot;, k = 1
28+
<strong>Output:</strong> 6
29+
<strong>Explanation:</strong> &quot;000001&quot; is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal.
30+
The length of this subsequence is 6, so 6 is returned.
31+
</pre>
32+
33+
<p>&nbsp;</p>
34+
<p><strong>Constraints:</strong></p>
35+
36+
<ul>
37+
<li><code>1 &lt;= s.length &lt;= 1000</code></li>
38+
<li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li>
39+
<li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li>
40+
</ul>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Approach: Greedy
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def longestSubsequence(self, s: str, k: int) -> int:
8+
sm = 0
9+
cnt = 0
10+
bits = k.bit_length()
11+
12+
for i, ch in enumerate(s[::-1]):
13+
if ch == '1':
14+
if i < bits and sm + (1 << i) <= k:
15+
sm += 1 << i
16+
cnt += 1
17+
else:
18+
cnt += 1
19+
20+
return cnt
21+

0 commit comments

Comments
 (0)