Skip to content

2395. Longest Binary Subsequence Less Than Or Equal To K

Difficulty: Medium

LeetCode Problem View on GitHub


2395. Longest Binary Subsequence Less Than or Equal to K

Medium


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 zeroes.
  • The empty string is considered to be equal to 0.
  • 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.

 

Example 1:

Input: s = "1001010", k = 5
Output: 5
Explanation: The longest subsequence of s that makes up a binary number less than or equal to 5 is "00010", as this number is equal to 2 in decimal.
Note that "00100" and "00101" are also possible, which are equal to 4 and 5 in decimal, respectively.
The length of this subsequence is 5, so 5 is returned.

Example 2:

Input: s = "00101001", k = 1
Output: 6
Explanation: "000001" is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal.
The length of this subsequence is 6, so 6 is returned.

 

Constraints:

  • 1 <= s.length <= 1000
  • s[i] is either '0' or '1'.
  • 1 <= k <= 109

Solution

import java.util.Arrays;

class Solution {
    private int dp[][];
    public int longestSubsequence(String s, int k) {
        int n = s.length();
        dp = new int[n + 1][n + 1];
        for (int current[] : dp)
            Arrays.fill(current, -1);
        return solve(n - 1, 0, 0, k, s);
    }

    private int solve(int ind, long val, int pos, int k, String s) {
        if (ind < 0)
            return 0;
        if (dp[ind][pos] != -1)
            return dp[ind][pos];

        int op1 = 0, op2 = 0;
        op1 = solve(ind - 1, val, pos, k, s);
        if (s.charAt(ind) == '0')
            op2 = 1 + solve(ind - 1, val, pos + 1, k, s);
        else if (s.charAt(ind) == '1') {
            if (pos < 33 && (val + (1L << pos)) <= k)
                op2 = 1 + solve(ind - 1, val + (1L << pos), pos + 1, k, s);
        }
        return dp[ind][pos] = Math.max(op2, op1);
    }
}

Complexity Analysis

  • Time Complexity: O(?)
  • Space Complexity: O(?)

Approach

Detailed explanation of the approach will be added here