[Leetcode] 2311. Longest Binary Subsequence Less Than or Equal to K

whitehousechef·2025년 6월 26일

https://leetcode.com/problems/longest-binary-subsequence-less-than-or-equal-to-k/?envType=daily-question&envId=2025-06-26

initial

I thought it was a contiguous subarray but its a subsequence, which means we can either take or delete any character while preserving the order

sol

we can take greedily any 1 or 0 as long as the current number is k. But we cannot exceed k so once we get as close to k as possible, we can take any 0s cuz that will not increment the current value.

also very impt we need to put brackets around hola << power. I thought the bit operations take precedence over addition but when i dont put bracket, it calculates as (ans+hola)<< power, which is wrong.

class Solution:
    def longestSubsequence(self, s: str, k: int) -> int:
        ans=0
        power=0
        count=0
        for i in range(len(s)-1,-1,-1):
            hola=int(s[i])
            # tmp is doing (ans+hola)<< power
            # correct way is putting brackets around hola << power
            tmp = ans + hola << power
            tmp2= hola<<power
            if ans+ (hola<<power) <=k :
                ans+= hola<<power
                count+=1
                power+=1
        return count

        

complexity

n time
1space

0개의 댓글