From 8717014c906e7b146cf378ffe1d397416f08a37c Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 14 Mar 2024 23:37:08 +0100 Subject: [PATCH] =?UTF-8?q?rs:=20add=20=C2=AB930.=20Binary=20Subarrays=20W?= =?UTF-8?q?ith=20Sum=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- rs/binary-subarrays-with-sum.rs | 34 +++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 rs/binary-subarrays-with-sum.rs diff --git a/rs/binary-subarrays-with-sum.rs b/rs/binary-subarrays-with-sum.rs new file mode 100644 index 0000000..4855be2 --- /dev/null +++ b/rs/binary-subarrays-with-sum.rs @@ -0,0 +1,34 @@ +impl Solution { + pub fn num_subarrays_with_sum(nums: Vec, goal: i32) -> i32 { + let mut subarrays = 0; + + let mut sum = 0; + let mut zeros = 0; + + let mut l = 0; + for r in 0..nums.len() { + sum += nums[r]; + + while l < r && (nums[l] == 0 || sum > goal) { + match nums[l] { + 0 => { + zeros += 1; + } + 1 => { + zeros = 0; + } + _ => unreachable!("either 0 or 1s"), + } + + sum -= nums[l]; + l += 1; + } + + if sum == goal { + subarrays += 1 + zeros; + } + } + + subarrays + } +}