Skip to content

Commit

Permalink
Add problem 1498: Number of Subsequences That Satisfy the Given Sum C…
Browse files Browse the repository at this point in the history
…ondition
  • Loading branch information
Spxg committed Dec 19, 2024
1 parent 6e8f240 commit 45ef8ac
Show file tree
Hide file tree
Showing 3 changed files with 69 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 @@ -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;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
pub mod two_pointer_and_math;

pub trait Solution {
fn num_subseq(nums: Vec<i32>, target: i32) -> i32;
}

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

pub fn run<S: Solution>() {
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);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
pub struct Solution;

impl Solution {
pub fn num_subseq(nums: Vec<i32>, 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<i32>, target: i32) -> i32 {
Self::num_subseq(nums, target)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}

0 comments on commit 45ef8ac

Please sign in to comment.