Link Search Menu Expand Document

1534. Count Good Triplets

Solution Code

C#

public class Solution {
    public int CountGoodTriplets(int[] arr, int a, int b, int c) {
        int size = arr.Length, count = 0;
        
        for (int i = 0; i < size; i++) {
            for (int j = i + 1; j < size; j++) {
                for (int k = j + 1; k < size; k++) {
                    bool isGoodTriplet = Math.Abs(arr[i] - arr[j]) <= a
                        && Math.Abs(arr[j] - arr[k]) <= b
                        && Math.Abs(arr[i] - arr[k]) <= c;
                        
                    if (isGoodTriplet)
                        count++;
                }
            }
        }
        
        return count;
    }
}

C++

class Solution {
public:
    int countGoodTriplets(vector<int>& arr, int a, int b, int c) {
        int size = arr.size(), count = 0;
        
        for (int i = 0; i < size; i++) {
            for (int j = i + 1; j < size; j++) {
                for (int k = j + 1; k < size; k++) {
                    bool isGoodTriplet = abs(arr[i] - arr[j]) <= a
                        && abs(arr[j] - arr[k]) <= b
                        && abs(arr[i] - arr[k]) <= c;
                        
                    if (isGoodTriplet)
                        count++;
                }
            }
        }
        
        return count;
    }
};

Java

class Solution {
    public int countGoodTriplets(int[] arr, int a, int b, int c) {
        int size = arr.length, count = 0;
        
        for (int i = 0; i < size; i++) {
            for (int j = i + 1; j < size; j++) {
                for (int k = j + 1; k < size; k++) {
                    boolean isGoodTriplet = Math.abs(arr[i] - arr[j]) <= a
                        && Math.abs(arr[j] - arr[k]) <= b
                        && Math.abs(arr[i] - arr[k]) <= c;
                        
                    if (isGoodTriplet)
                        count++;
                }
            }
        } 

        return count;
    }
}

© 2023. All rights reserved.