Creating countTriplets Function

We need nested loops in this function. As we say before, we will run three loops to consider all triplets one by one.

 static int countTriplets(int[] arr, int n, int sum)
{
    // Initialize result
    int ans = 0;

    // Fix the first element as A[i]
    for (int i = 0; i < n - 2; i++)
    {
        // Fix the second element as A[j]
        for (int j = i + 1; j < n - 1; j++)
        {
            // Now look for the third number
            for (int k = j + 1; k < n; k++)

        }
    }
    return ans;
}

For every triplet, compare the sums and increment count if triplet sum is smaller than given sum.

// Now look for the third number
for (int k = j + 1; k < n; k++)
    if (arr[i] + arr[j] + arr[k] < sum)
        ans++;

This will resulting with right answer.

results matching ""

    No results matching ""