Skip to content

Instantly share code, notes, and snippets.

@nobuh
Created July 29, 2011 07:48
Show Gist options
  • Save nobuh/1113397 to your computer and use it in GitHub Desktop.
Save nobuh/1113397 to your computer and use it in GitHub Desktop.
Find maximum circumference of a triangles. An exercise of js
// Triangle.js
//
// Pick up 3 side numbers a[i] to make a triangle from n numbers.
// Find the maximum circumference of triangles.
//
// Constraints :
// 3 <= n <= 100
// 1 <= a[i] <= 10^6
var TRI = {};
TRI.solve = function (n, a) {
var ans = 0;
// i < j < k to prevent to pick same number
for (var i = 0; i < n; i++) {
for (var j = i + 1; j < n; j++) {
for (var k = j + 1; k < n; k++) {
var len = a[i] + a[j] + a[k];
var longest = Math.max(a[i], a[j], a[k]);
var rest = len - longest;
// longest side a < b + c must be a triangle.
if (longest < rest) {
ans = Math.max(ans, len);
}
}
}
}
return ans;
};
// Test 1 : n = 5, a = {2, 3, 4, 5, 10}, answer = 12
// Test 2 : n = 4, a = {4, 5, 10, 20}, answer = 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment