Advertisement
1534. Count Good Triplets
EasyView on LeetCode
Time: O(n³)
Space: O(1)
Approach
Brute-force O(n³) check all triplets i<j<k satisfying all three difference constraints.
1534.cs
C#
// Approach: Brute-force O(n³) check all triplets i<j<k satisfying all three difference constraints.
// Time: O(n³) Space: O(1)
public class Solution
{
public int CountGoodTriplets(int[] arr, int a, int b, int c)
{
int ans = 0;
for (int i = 0; i < arr.Length; ++i)
{
for (int j = i + 1; j < arr.Length; ++j)
{
for (int k = j + 1; k < arr.Length; ++k)
{
if (Math.Abs(arr[i] - arr[j]) <= a &&
Math.Abs(arr[j] - arr[k]) <= b &&
Math.Abs(arr[i] - arr[k]) <= c)
++ans;
}
}
}
return ans;
}
}Advertisement
Was this solution helpful?