2221. Find Triangular Sum of an Array #2234
-
Topics: You are given a 0-indexed integer array The triangular sum of
Return the triangular sum of Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the triangular sum of an array by repeatedly reducing the array until only one element remains. Each reduction step involves creating a new array where each element is the sum of two adjacent elements modulo 10. Approach
Let's implement this solution in PHP: 2221. Find Triangular Sum of an Array <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function triangularSum($nums) {
$n = count($nums);
while ($n > 1) {
for ($i = 0; $i < $n - 1; $i++) {
$nums[$i] = ($nums[$i] + $nums[$i + 1]) % 10;
}
$n--;
}
return $nums[0];
}
// Test cases
// Example 1
$nums1 = array(1, 2, 3, 4, 5);
echo "Input: [1,2,3,4,5]\n";
echo "Output: " . triangularSum($nums1) . "\n"; // Expected 8
// Example 2
$nums2 = array(5);
echo "Input: [5]\n";
echo "Output: " . triangularSum($nums2) . "\n"; // Expected 5
?> Explanation:
This approach efficiently computes the triangular sum by leveraging in-place updates, ensuring optimal space usage while maintaining clarity and simplicity in the solution. The time complexity is O(n²) due to the nested loops, which is acceptable given the constraints (array length up to 1000). |
Beta Was this translation helpful? Give feedback.
We need to find the triangular sum of an array by repeatedly reducing the array until only one element remains. Each reduction step involves creating a new array where each element is the sum of two adjacent elements modulo 10.
Approach