Created
March 2, 2015 08:25
-
-
Save rohith2506/58b0f4620dfc054f5775 to your computer and use it in GitHub Desktop.
Count the number of possible triangles
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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