[InterviewBit] Counting Triangles

Counting Triangles

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int Solution::nTriang(vector<int> &A) {
sort(begin(A), end(A));
long long res = 0, mod = 1e9 + 7;
for(int i = A.size() - 1; i >= 2; i--) {
int l = 0, r = i - 1;
while(l < r) {
int sum = A[l] + A[r];
if(sum > A[i]) {
res = (res + (r - l) % mod) % mod;
r--;
} else l++;
}
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/17/PS/interviewbit/counting-triangles/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.