703299. Sum Triangle for given array
Basic
Sum Triangle for given array1159
Summary
Given an array, we need to find the sum of all triangles that can be formed using the elements of the array. A triangle is considered valid if it has three sides and its area is non-negative.
Detailed Explanation
To solve this problem, we will use a brute force approach. First, we generate all possible combinations of three elements from the given array. Then, for each combination, we check if the sum of the three elements forms a valid triangle (i.e., the sum is positive). If it does, we add its area to our total sum.
Here's a step-by-step breakdown:
- Initialize an empty set
trianglesto store the sum of all triangles. - Generate all possible combinations of three elements from the given array using a combination algorithm (e.g., recursive approach).
- For each combination, calculate the sum of its elements and check if it forms a valid triangle by verifying the condition
a + b > c, wherea,b, andcare the sides of the triangle. - If the combination forms a valid triangle, add its area to the set
triangles. - Finally, return the sum of all triangles in the set.
Time complexity: O(n^3), where n is the length of the input array.
Space complexity: O(1), since we only need a constant amount of space to store the set triangles.
Optimized Solutions
Java
java
import java.util.*;
public class SumTriangle {
public static int sumTriangle(int[] arr) {
Set<Integer> triangles = new HashSet<>();
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
for (int k = j + 1; k < arr.length; k++) {
int sum = arr[i] + arr[j] + arr[k];
if (sum > 0) {
triangles.add(sum);
}
}
}
}
return triangles.stream().mapToInt(Integer::intValue).sum();
}
}
Python
python
def sum_triangle(arr):
triangles = set()
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
for k in range(j + 1, len(arr)):
sum_val = arr[i] + arr[j] + arr[k]
if sum_val > 0:
triangles.add(sum_val)
return sum(triangles)
C++
cpp
#include <iostream>
#include <set>
int sumTriangle(int* arr, int n) {
std::set<int> triangles;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
int sum = arr[i] + arr[j] + arr[k];
if (sum > 0) {
triangles.insert(sum);
}
}
}
}
int result = 0;
for (auto it = triangles.begin(); it != triangles.end(); ++it) {
result += *it;
}
return result;
}
JavaScript
javascript
function sumTriangle(arr) {
const triangles = new Set();
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
for (let k = j + 1; k < arr.length; k++) {
const sum = arr[i] + arr[j] + arr[k];
if (sum > 0) {
triangles.add(sum);
}
}
}
}
return [...triangles].reduce((acc, cur) => acc + cur, 0);
}
Not available