From 0af3b7c97c98d1e13c0170d900cbeb8d97f84ec5 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Wed, 25 Jun 2025 19:23:59 -0600 Subject: 2311. longest binary subsequence less than or equal to k --- longest_binary_subseq_leq_k.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 longest_binary_subseq_leq_k.py (limited to 'longest_binary_subseq_leq_k.py') diff --git a/longest_binary_subseq_leq_k.py b/longest_binary_subseq_leq_k.py new file mode 100644 index 0000000..e07204a --- /dev/null +++ b/longest_binary_subseq_leq_k.py @@ -0,0 +1,29 @@ +# 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 zeros, the +empty string is considered to be equal to 0, and 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. +""" + + +class Solution(object): + def longestSubsequence(self, s, k): + """ + :type s: str + :type k: int + :rtype: int + """ + i = 0 + while int(s[-i - 1 :], 2) <= k and i < 32 and i < len(s): + i += 1 + return s[:-i].count("0") + i + + +if __name__ == "__main__": + obj = Solution() + print(obj.longestSubsequence(s="1001010", k=5)) + print(obj.longestSubsequence(s="00101001", k=1)) -- cgit v1.2.3