Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 113a508

Browse files
Add solution for Binary Subarrays With Sum
1 parent 31cb635 commit 113a508

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

‎README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,9 @@ Algorithm exercises from LeetCode implemented in Java v11.
8383
- Merge Sorted Array | [Problem](https://leetcode.com/problems/merge-sorted-array) | [Solution](src/solutions/MergeSortedArray.java)
8484
- Partition Labels | [Problem](https://leetcode.com/problems/partition-labels) | [Solution](src/solutions/PartitionLabels.java)
8585

86+
### Sliding Window
87+
- Binary Subarrays With Sum | [Problem](https://leetcode.com/problems/binary-subarrays-with-sum) | [Solution](src/solutions/BinarySubarraysWithSum.java)
88+
8689
### Recursion
8790
- Closest Binary Search Tree Value | [Problem](https://leetcode.com/problems/closest-binary-search-tree-value)
8891
- Subtree Of Another Tree | [Problem](https://leetcode.com/problems/subtree-of-another-tree) | [Solution](src/solutions/SubtreeOfAnotherTree.java)
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /