|
| 1 | +package solutions; |
| 2 | + |
| 3 | +// [Problem] https://leetcode.com/problems/binary-subarrays-with-sum |
| 4 | +class BinarySubarraysWithSum { |
| 5 | + // Sliding window |
| 6 | + // O(n) time, O(1) space |
| 7 | + public int numSubarraysWithSum(int[] nums, int goal) { |
| 8 | + int count = 0, sum = 0, left = 0; |
| 9 | + for (int right = 0; right < nums.length; right++) { |
| 10 | + sum += nums[right]; |
| 11 | + while (left < right && sum > goal) { |
| 12 | + sum -= nums[left++]; |
| 13 | + } |
| 14 | + if (sum == goal) { |
| 15 | + count++; |
| 16 | + for (int i = left; i < right && nums[i] == 0; i++) { |
| 17 | + count++; |
| 18 | + } |
| 19 | + } |
| 20 | + } |
| 21 | + return count; |
| 22 | + } |
| 23 | + |
| 24 | + // Test |
| 25 | + public static void main(String[] args) { |
| 26 | + BinarySubarraysWithSum solution = new BinarySubarraysWithSum(); |
| 27 | + |
| 28 | + int[] nums1 = {1, 0, 1, 0, 1}; |
| 29 | + int goal1 = 2; |
| 30 | + int expectedOutput1 = 4; |
| 31 | + int actualOutput1 = solution.numSubarraysWithSum(nums1, goal1); |
| 32 | + System.out.println("Test 1 passed? " + (expectedOutput1 == actualOutput1)); |
| 33 | + |
| 34 | + int[] nums2 = {0, 0, 0, 0, 0}; |
| 35 | + int goal2 = 0; |
| 36 | + int expectedOutput2 = 15; |
| 37 | + int actualOutput2 = solution.numSubarraysWithSum(nums2, goal2); |
| 38 | + System.out.println("Test 2 passed? " + (expectedOutput2 == actualOutput2)); |
| 39 | + } |
| 40 | +} |
0 commit comments