-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberOfPossibleTriangles.java
More file actions
76 lines (62 loc) · 2.1 KB
/
NumberOfPossibleTriangles.java
File metadata and controls
76 lines (62 loc) · 2.1 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/***********************************************************************************************
*
* Count the number of possible triangles
*
* Given an unsorted array arr[] of n positive integers. Find the number of triangles
* that can be formed with three different array elements as lengths of three sides
* of triangles.
*
* Example 1:
*
* Input:
* n = 3
* arr[] = {3, 5, 4}
* Output:
* 1
* Explanation:
* A triangle is possible
* with all the elements 5, 3 and 4.
*
* Your Task:
* This is a function problem. You only need to complete the function findNumberOfTriangles()
* that takes arr[] and n as input parameters and returns the count of total possible triangles.
*
*************************************************************************************************/
import java.util.Arrays;
public class NumberOfPossibleTriangles {
public static void main(String[] args) {
NumberOfPossibleTriangles possibleTriangles = new NumberOfPossibleTriangles();
int n = 6;
int arr[] = {26, 9, 27, 22, 16, 27};
System.out.println(possibleTriangles.findNumberOfTrianglesOptimized(arr, n));
}
int findNumberOfTriangles(int arr[], int n) {
int result = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
if (arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[j] + arr[k] > arr[i]) {
result++;
}
}
}
}
return result;
}
int findNumberOfTrianglesOptimized(int arr[], int n) {
int result = 0;
Arrays.sort(arr);
for (int i = 0; i < n; i++) {
int k = i + 2;
for (int j = i + 1; j < n; j++) {
while (k < n && arr[i] + arr[j] > arr[k]) {
k++;
}
if (k > j){
result += k - j - 1;
}
}
}
return result;
}
}