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

2311. Longest Binary Subsequence Less Than or Equal to K

Leetcode Solutions

Greedy Approach with Reverse Traversal

  1. Initialize val to 0, cnt to 0, and pow to 1. These variables will keep track of the current value of the binary number, the count of '1's included, and the current power of 2, respectively.
  2. Iterate over the string s from right to left.
  3. For each character, check if it is a '1' and if adding it to val (multiplied by pow) would not exceed k.
  4. If it does not exceed, increment cnt, add pow to val, and double pow.
  5. If it exceeds or the character is a '0', just double pow without changing cnt or val.
  6. After the loop, count the number of '0's in the entire string and add cnt to it to get the result.
  7. Return the result as the length of the longest subsequence.
UML Thumbnail

Dynamic Programming Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...