Skip to content

2311. Longest Binary Subsequence Less Than or Equal to K 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int longestSubsequence(string s, int k) {
    int oneCount = 0;
    int num = 0;
    int pow = 1;

    // Take as many 1s as possible from the right.
    for (int i = s.length() - 1; i >= 0 && num + pow <= k; --i) {
      if (s[i] == '1') {
        ++oneCount;
        num += pow;
      }
      pow *= 2;
    }

    return ranges::count(s, '0') + oneCount;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int longestSubsequence(String s, int k) {
    int oneCount = 0;
    int num = 0;
    int pow = 1;

    // Take as many 1s as possible from the right.
    for (int i = s.length() - 1; i >= 0 && num + pow <= k; --i) {
      if (s.charAt(i) == '1') {
        ++oneCount;
        num += pow;
      }
      pow *= 2;
    }

    return (int) s.chars().filter(c -> c == '0').count() + oneCount;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def longestSubsequence(self, s: str, k: int) -> int:
    oneCount = 0
    num = 0
    pow = 1

    # Take as many 1s as possible from the right.
    for i in reversed(range(len(s))):
      if num + pow > k:
        break
      if s[i] == '1':
        oneCount += 1
        num += pow
      pow *= 2

    return s.count('0') + oneCount