JavaScript - Explained With Comments And Visualization
There is a great rule that\'s called Traingle Inequality and it states the following:\n\nIn mathematics, the triangle inequality states that for any triangle, t
There is a great rule that\'s called **Traingle Inequality** and it states the following:\n\n**In mathematics, the triangle inequality states that for any triangle, the sum of the lengths of any two sides must be greater than the length of the remaining side.**\n**If x, y, and z are the lengths of the sides of the triangle, with no side being greater than z, then the triangle inequality states that z < x + y**\n\nFor example, we can take the next triangle for visualization:\n\n![image](https://assets.leetcode.com/users/images/411d9368-fecd-4970-b462-fcd2f2b1bde1_1665556972.1866663.png)\n\nThe rule states that **x + y > z**.\n\nTo answer the question, we first of all can sort the array in decreasing order, because we know that if **x + y > z**, then **x + z > y also**.\nAfter that, we will loop through the array, we will declare three variables that will indicate the three sides of a triangle.\nIf the sum b + c is greater than a (the last side of the triangle), then we know we have an answer (we just go by the rule I stated above).\n\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar largestPerimeter = function(nums) {    \n\t// Sort in DESC order\n    nums.sort((a, b) => b - a);\n        \n    for(let i = 0; i < nums.length; i++) {\n\t\n\t\t// Decalre the three sides of the triangle\n        let a = nums[i], b = nums[i + 1], c = nums[i + 2];\n        \n\t\t// Perform the check depending on the rule\n        if(a < b + c) return a + b + c;\n    }\n    \n\t// If we cannot form a triangle, we return 0\n    return 0;\n};\n```
['JavaScript']