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.
Conditions for a valid triangle:
1 <= nums.length <= 10000 <= nums[i] <= 1000Multiple approaches are provided, from brute force to optimized:
Approach 1: Brute Force (3 nested loops)
Approach 2: Sort + Triple Nested Loop
Approach 3: Sort + Two Pointers (Optimized)
Why this approach works:
Alternative approaches considered:
Example Input: nums = [2, 2, 3, 4]
Approach 3 (Optimized) Dry Run:
Final Answer = 2
/**
* ---------------------------------------------------------------------------
* Approach 1: Brute Force (3 nested loops)
* ---------------------------------------------------------------------------
*/
class SolutionBruteForce {
public int triangleNumber(int[] nums) {
int count = 0;
for (int i = 0; i < nums.length - 2; i++) {
for (int j = i + 1; j < nums.length - 1; j++) {
for (int k = j + 1; k < nums.length; k++) {
int a = nums[i];
int b = nums[j];
int c = nums[k];
if ((a + b > c) && (a + c > b) && (b + c > a)) {
count++;
}
}
}
}
return count;
}
}
/**
* ---------------------------------------------------------------------------
* Approach 2: Sort + Triple Nested Loop
* ---------------------------------------------------------------------------
*/
class SolutionSortedTriple {
public int triangleNumber(int[] nums) {
Arrays.sort(nums);
int count = 0;
for (int i = 0; i < nums.length - 2; i++) {
for (int j = i + 1; j < nums.length - 1; j++) {
for (int k = j + 1; k < nums.length; k++) {
if (nums[i] + nums[j] > nums[k]) {
count++;
}
}
}
}
return count;
}
}
/**
* ---------------------------------------------------------------------------
* Approach 3: Sort + Two Pointers (Optimized)
* ---------------------------------------------------------------------------
*/
class SolutionOptimized {
public int triangleNumber(int[] nums) {
Arrays.sort(nums);
int count = 0;
for (int i = nums.length - 1; i >= 2; i--) {
int j = 0, k = i - 1;
while (j < k) {
if (nums[j] + nums[k] > nums[i]) {
count += k - j;
k--;
} else {
j++;
}
}
}
return count;
}
}