diff --git a/src/lib.rs b/src/lib.rs index 8013bca..3a2866f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -568,6 +568,7 @@ pub mod problem_1476_subrectangle_queries; pub mod problem_1481_least_number_of_unique_integers_after_k_removals; pub mod problem_1486_xor_operation_in_an_array; pub mod problem_1487_making_file_names_unique; +pub mod problem_1498_number_of_subsequences_that_satisfy_the_given_sum_condition; pub mod problem_1507_reformat_date; pub mod problem_1508_range_sum_of_sorted_subarray_sums; pub mod problem_1524_number_of_sub_arrays_with_odd_sum; diff --git a/src/problem_1498_number_of_subsequences_that_satisfy_the_given_sum_condition/mod.rs b/src/problem_1498_number_of_subsequences_that_satisfy_the_given_sum_condition/mod.rs new file mode 100644 index 0000000..d4c7a3f --- /dev/null +++ b/src/problem_1498_number_of_subsequences_that_satisfy_the_given_sum_condition/mod.rs @@ -0,0 +1,23 @@ +pub mod two_pointer_and_math; + +pub trait Solution { + fn num_subseq(nums: Vec, target: i32) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + ((&[3, 5, 6, 7] as &[_], 9), 4), + ((&[3, 3, 6, 8], 10), 6), + ((&[2, 3, 3, 4, 6, 7], 12), 61), + ((&[5, 2, 4, 1, 7, 6, 8], 16), 127), + ]; + + for ((nums, target), expected) in test_cases { + assert_eq!(S::num_subseq(nums.to_vec(), target), expected); + } + } +} diff --git a/src/problem_1498_number_of_subsequences_that_satisfy_the_given_sum_condition/two_pointer_and_math.rs b/src/problem_1498_number_of_subsequences_that_satisfy_the_given_sum_condition/two_pointer_and_math.rs new file mode 100644 index 0000000..7ec4eab --- /dev/null +++ b/src/problem_1498_number_of_subsequences_that_satisfy_the_given_sum_condition/two_pointer_and_math.rs @@ -0,0 +1,45 @@ +pub struct Solution; + +impl Solution { + pub fn num_subseq(nums: Vec, target: i32) -> i32 { + let modulo = 1_000_000_007; + + let mut result = 0; + let mut nums = nums; + nums.sort_unstable(); + + let mut pow2 = vec![1; nums.len()]; + for i in 1..nums.len() { + pow2[i] = (pow2[i - 1] * 2) % modulo; + } + + let (mut left, mut right) = (0, nums.len() - 1); + while left <= right { + if nums[left] + nums[right] <= target { + result = (result + pow2[right - left]) % modulo; + left += 1; + } else { + if right == 0 { + break; + }; + right -= 1; + } + } + + result + } +} + +impl super::Solution for Solution { + fn num_subseq(nums: Vec, target: i32) -> i32 { + Self::num_subseq(nums, target) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +}