Skip to content

Commit 23a6606

Browse files
committed
#3392: Count Subarrays of Length Three With a Condition; solution & tests
1 parent 8920316 commit 23a6606

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* 3392
3+
* Count Subarrays of Length Three With a Condition
4+
**
5+
* Given an integer array nums,
6+
* return the number of subarrays of length 3
7+
* such that the sum of the first and third numbers
8+
* equals exactly half of the second number.
9+
*
10+
* Example 1:
11+
* Input: nums = [1,2,1,4,1]
12+
* Output: 1
13+
* Explanation:
14+
* Only the subarray [1,4,1] contains exactly 3 elements
15+
* where the sum of the first and third numbers equals half the middle number.
16+
*
17+
* Example 2:
18+
* Input: nums = [1,1,1]
19+
* Output: 0
20+
* Explanation:
21+
* [1,1,1] is the only subarray of length 3.
22+
* However,
23+
* its first and third numbers do not add to half the middle number.
24+
*
25+
* Constraints:
26+
* • 3 <= nums.length <= 100
27+
* • -100 <= nums[i] <= 100
28+
*
29+
* Hint 1:
30+
* The constraints are small. Consider checking every subarray.
31+
**
32+
* https://leetcode.com/problems/count-subarrays-of-length-three-with-a-condition/
33+
***/
34+
35+
namespace Problems;
36+
37+
public class CountSubarraysOfLengthThreeWithACondition
38+
{
39+
public int CountSubarrays( int[] nums )
40+
{
41+
int count = 0;
42+
43+
for ( int i = 2; i < nums.Length; i++ )
44+
{
45+
if ( ( nums[i] + nums[i - 2] ) * 2 == nums[i - 1] )
46+
{
47+
count++;
48+
}
49+
}
50+
51+
return count;
52+
}
53+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
using NUnit.Framework;
2+
3+
using Problems;
4+
5+
public class CountSubarraysOfLengthThreeWithAConditionTests
6+
{
7+
[TestCase( new int[] { 1, 2, 1, 4, 1 }, ExpectedResult = 1 )]
8+
[TestCase( new int[] { 1, 1, 1 }, ExpectedResult = 0 )]
9+
[TestCase( new int[] { 0, -4, -4 }, ExpectedResult = 0 )]
10+
[TestCase( new int[] { -1, -4, -1, 4 }, ExpectedResult = 1 )]
11+
public int CountSubarraysTest( int[] nums ) =>
12+
new CountSubarraysOfLengthThreeWithACondition().CountSubarrays( nums );
13+
}

0 commit comments

Comments
 (0)