-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberOfTriangles.cs
More file actions
49 lines (44 loc) · 1.57 KB
/
Copy pathNumberOfTriangles.cs
File metadata and controls
49 lines (44 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
namespace DA.Algorithms.Problems
{
public static class NumberOfTriangles
{
/// <summary>
/// Find the number of triangles that can be formed from
/// elements of the array representing sides of triangles.
/// <para>Time Complexity - O(n^3)</para>
/// </summary>
public static int GetNumberOfTriangles (int[] array)
{
int count = 0;
for (int i = 0; i < array.Length - 2; i++)
for (int j = i + 1; j < array.Length - 1; j++)
for (int k = j + 1; k < array.Length; k++)
if (array[i] + array[j] > array[k])
++count;
return count;
}
/// <summary>
/// Find the number of triangles that can be formed from
/// elements of the array representing sides of triangles.
/// <para>Time Complexity - O(n^2)</para>
/// </summary>
public static int GetNumberOfTrianglesUsingSorting (int[] array)
{
int count = 0, currentIndex = 0;
for (int i = 0; i < array.Length - 2; i++)
{
currentIndex = i + 2;
for (int j = i + 1; j < array.Length - 1; j++)
{
while (currentIndex < array.Length
&& array[i] + array[j] > array[currentIndex])
{
++currentIndex;
}
count += currentIndex - j - 1;
}
}
return count;
}
}
}