2311. Longest Binary Subsequence Less Than or Equal to K #1854
-
Topics: You are given a binary string Return the length of the longest subsequence of Note:
Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the length of the longest subsequence of a given binary string that forms a binary number less than or equal to a positive integer k. The solution involves efficiently exploring possible subsequences while maximizing their length under the constraint that their numeric value does not exceed k. Approach
Let's implement this solution in PHP: 2311. Longest Binary Subsequence Less Than or Equal to K <?php
/**
* @param String $s
* @param Integer $k
* @return Integer
*/
function longestSubsequence($s, $k) {
$n = strlen($s);
$total_zeros = 0;
for ($i = 0; $i < $n; $i++) {
if ($s[$i] == '0') {
$total_zeros++;
}
}
$prefix_zeros = array_fill(0, $n + 1, 0);
for ($i = 0; $i < $n; $i++) {
$prefix_zeros[$i + 1] = $prefix_zeros[$i] + ($s[$i] == '0' ? 1 : 0);
}
$best = $total_zeros;
for ($i = 0; $i < $n; $i++) {
if ($s[$i] != '1') {
continue;
}
$cur_val = 1;
$cur_len = 1;
$zeros_before = $prefix_zeros[$i];
for ($j = $i + 1; $j < $n; $j++) {
if ($cur_val > $k) {
break;
}
if ($s[$j] == '0') {
$new_val = $cur_val * 2;
if ($new_val <= $k) {
$cur_val = $new_val;
$cur_len++;
}
} else {
$new_val = $cur_val * 2 + 1;
if ($new_val <= $k) {
$cur_val = $new_val;
$cur_len++;
}
}
}
$total_len = $zeros_before + $cur_len;
if ($total_len > $best) {
$best = $total_len;
}
}
return $best;
}
// Example test cases
echo longestSubsequence("1001010", 5) . "\n"; // Output: 5
echo longestSubsequence("00101001", 1) . "\n"; // Output: 6
?> Explanation:
This approach efficiently explores all potential subsequences, leveraging early termination to optimize performance, and ensures the solution meets the problem constraints. |
Beta Was this translation helpful? Give feedback.
We need to find the length of the longest subsequence of a given binary string that forms a binary number less than or equal to a positive integer k. The solution involves efficiently exploring possible subsequences while maximizing their length under the constraint that their numeric value does not exceed k.
Approach
Problem Analysis: The problem requires selecting a subsequence (not necessarily contiguous) from the binary string such that the binary number formed by the subsequence is ≤ k. The subsequence can include leading zeros, which do not affect the numeric value but contribute to the length. The challenge is to maximize the length of such a subsequence.
Key Insight: The solut…