알고리즘

Count Good Triplets

짬뽕얼큰하게 2025. 4. 14. 21:03

Leetcode Problem:

Summary

  • Find the number of good triplets in an array of integers given three integers a, b, and c.

Approach

  • Three nested loops are used to iterate through the array and check each triplet against the conditions
  • The absolute difference between each pair of numbers is calculated and compared to the given integers a, b, and c
  • If all conditions are met, the triplet is counted.

Complexity

  • O(n^3) where n is the size of the array

Explanation

  • The solution uses three nested loops to iterate through the array
  • The outer loop starts at the first element, the middle loop starts at the next element after the outer loop, and the inner loop starts at the next element after the middle loop
  • The solution checks each triplet against the conditions and increments the count if all conditions are met.

Solution Code:


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

            }
        }
        return ans;
    }
};