Last active
September 26, 2025 16:38
-
-
Save tatsuyax25/2db709ce6470f194e9cdaa1728d2d43c to your computer and use it in GitHub Desktop.
Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.
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
| /** | |
| * @param {number[]} nums | |
| * @return {number} | |
| */ | |
| var triangleNumber = function(nums) { | |
| // Step 1: Sort the array to simplify triangle inequality checks | |
| nums.sort((a, b) => a - b); | |
| let count = 0; | |
| let n = nums.length; | |
| // Step 2: Fix the largest side of the triangle at index k | |
| for (let k = n - 1; k >= 2; k--) { | |
| let i = 0; // Start pointer | |
| let j = k - 1; // End pointer before k | |
| // Step 3: Use two pointers to find valid pairs (i, j) such that nums[i] + nums[j] > nums[k] | |
| while (i < j) { | |
| if (nums[i] + nums[j] > nums[k]) { | |
| // All elements between i and j are valid with j and k | |
| count += (j - i); | |
| j--; // Try a smaller j to find more combinations | |
| } else { | |
| i++; // Increase i to make the sum larger | |
| } | |
| } | |
| } | |
| return count; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment