611. Valid Triangle Number
Problem description:
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.
Example 1:
1 | Input: nums = [2,2,3,4] |
Example 2:
1 | Input: nums = [4,2,3,4] |
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] <= 1000
Solution:
Example:
arr = [3, 4, 6, 38, 39 ]
now your low = 3
, high = 38
, arr[i] = 39
Triangle inequality says that any 2 sides of triangle should be greater than the 3rd side.
you now know that your array is sorted so
3 + 38 > 39 [3, 38, 39]and the numbers which would come after 3 would be greater than 3 so next possible sides of triangles would include
[4, 38, 39] , [6, 38, 39]. That is why you add the difference of
high - low` which is in this case 3 - 0 = 3 possible sides of triangles as shown above.
1 | class Solution: |
time complexity: $O(n)$
space complexity: $O()$
reference:
related problem: