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
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
n time
1space