Skip to content

Commit

Permalink
Add problem 2311: Longest Binary Subsequence Less Than or Equal to K
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 19, 2024
1 parent 4e3899e commit 617d06a
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1720,6 +1720,7 @@ pub mod problem_2305_fair_distribution_of_cookies;
pub mod problem_2306_naming_a_company;
pub mod problem_2309_greatest_english_letter_in_upper_and_lower_case;
pub mod problem_2310_sum_of_numbers_with_units_digit_k;
pub mod problem_2311_longest_binary_subsequence_less_than_or_equal_to_k;
pub mod problem_2315_count_asterisks;
pub mod problem_2316_count_unreachable_pairs_of_nodes_in_an_undirected_graph;
pub mod problem_2317_maximum_xor_after_operations;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn longest_subsequence(s: String, k: i32) -> i32 {
let s = s.as_bytes();
let n = s.len();
let k = k as u32;
let bits = 32 - k.leading_zeros() as usize;

if n < bits {
return n as _;
}

let (left, right) = s.split_at(n - bits);
let right = right.iter().fold(0, |right, &c| (right << 1) + u32::from(c & 1));
let length = bits as u16 - u16::from(right > k);

i32::from(left.iter().fold(length, |length, &c| length + u16::from(b'1' - c)))
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn longest_subsequence(s: String, k: i32) -> i32 {
Self::longest_subsequence(s, k)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
pub mod greedy;

pub trait Solution {
fn longest_subsequence(s: String, k: i32) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [
(("1001010", 5), 5),
(("00101001", 1), 6),
(
(
"101100011000010101011100011111111001011101000101000010001100101110010010011000100010001110011111000100100101110000100010010010100010",
978_095_074,
),
84,
),
(("0", 583_196_182), 1),
];

for ((s, k), expected) in test_cases {
assert_eq!(S::longest_subsequence(s.to_string(), k), expected);
}
}
}

0 comments on commit 617d06a

Please sign in to comment.