Skip to content

Instantly share code, notes, and snippets.

@rohith2506
Created March 2, 2015 08:25
Show Gist options
  • Save rohith2506/58b0f4620dfc054f5775 to your computer and use it in GitHub Desktop.
Save rohith2506/58b0f4620dfc054f5775 to your computer and use it in GitHub Desktop.
Count the number of possible triangles
// As though it looks like O(n^3) but it actally is O(n^2). because of k initialized outisde and does not depenv on j value.
int possible_triangles(vector<int> a){
int count = 0;
for(int i=0; i<n-2; i++){
int k = i+2;
for(int j=i+1; j<n; j++){
while(k < n && a[i] + a[j] > a[k]) ++k;
count = count + (k-j-1);
}
}
return count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment