LeetCode 2311: Longest Binary Subsequence Less Than or Equal to K Solution

Master LeetCode problem 2311 (Longest Binary Subsequence Less Than or Equal to K), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2311. Longest Binary Subsequence Less Than or Equal to K

Problem Explanation

Explanation:

To solve this problem, we can iterate through the binary string s and keep track of the longest subsequence that makes up a binary number less than or equal to k. We can use dynamic programming to store the length of the longest subsequence ending at each index.

  1. Initialize an array dp of length n+1, where n is the length of string s. Initialize dp[0] = 0.
  2. Iterate through the characters of s from left to right. For each character:
    • If the character is '0', update dp[i+1] = dp[i].
    • If the character is '1', update dp[i+1] = max(dp[i], dp[max(0, i-L)]) + 1, where L is the number of '1's that can be replaced with '0's to form a number less than or equal to k.
  3. Return the maximum value in the dp array.

Time complexity: O(n) Space complexity: O(n)

Solution Code

class Solution {
    public int longestSubsequence(String s, int k) {
        int n = s.length();
        int[] dp = new int[n+1];
        dp[0] = 0;
        int maxLen = 0;
        
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) == '0') {
                dp[i+1] = dp[i];
            } else {
                int L = Math.min(i, k-1);
                dp[i+1] = Math.max(dp[i], dp[Math.max(0, i-L)] + 1);
            }
            maxLen = Math.max(maxLen, dp[i+1]);
        }
        
        return maxLen;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2311 (Longest Binary Subsequence Less Than or Equal to K)?

This page provides optimized solutions for LeetCode problem 2311 (Longest Binary Subsequence Less Than or Equal to K) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2311 (Longest Binary Subsequence Less Than or Equal to K)?

The time complexity for LeetCode 2311 (Longest Binary Subsequence Less Than or Equal to K) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2311 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2311 in Java, C++, or Python.

Back to LeetCode Solutions