| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.CountGoodTriplets; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class CountGoodTripletsPrefixSum : ICountGoodTriplets |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n^2 + n * M) |
| | 19 | | /// Space complexity - O(M) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="arr"></param> |
| | 22 | | /// <param name="a"></param> |
| | 23 | | /// <param name="b"></param> |
| | 24 | | /// <param name="c"></param> |
| | 25 | | /// <returns></returns> |
| | 26 | | public int CountGoodTriplets(int[] arr, int a, int b, int c) |
| 2 | 27 | | { |
| 2 | 28 | | var result = 0; |
| 2 | 29 | | var sum = new int[1001]; |
| | 30 | |
|
| 22 | 31 | | for (var j = 0; j < arr.Length - 1; ++j) |
| 9 | 32 | | { |
| 68 | 33 | | for (var k = j + 1; k < arr.Length; ++k) |
| 25 | 34 | | { |
| 25 | 35 | | if (Math.Abs(arr[j] - arr[k]) > b) |
| 17 | 36 | | { |
| 17 | 37 | | continue; |
| | 38 | | } |
| | 39 | |
|
| 8 | 40 | | var left = Math.Max(0, Math.Max(arr[j] - a, arr[k] - c)); |
| 8 | 41 | | var right = Math.Min(1000, Math.Min(arr[j] + a, arr[k] + c)); |
| | 42 | |
|
| 8 | 43 | | if (left > right) |
| 0 | 44 | | { |
| 0 | 45 | | continue; |
| | 46 | | } |
| | 47 | |
|
| 8 | 48 | | if (left == 0) |
| 5 | 49 | | { |
| 5 | 50 | | result += sum[right]; |
| 5 | 51 | | } |
| | 52 | | else |
| 3 | 53 | | { |
| 3 | 54 | | result += sum[right] - sum[left - 1]; |
| 3 | 55 | | } |
| 8 | 56 | | } |
| | 57 | |
|
| 17996 | 58 | | for (var k = arr[j]; k <= 1000; ++k) |
| 8989 | 59 | | { |
| 8989 | 60 | | sum[k]++; |
| 8989 | 61 | | } |
| 9 | 62 | | } |
| | 63 | |
|
| 2 | 64 | | return result; |
| 2 | 65 | | } |
| | 66 | | } |