LeetCode 2221: Find Triangular Sum of an Array
Problem Description
Explanation:
To solve this problem, we iterate through the array nums
repeatedly until there is only one element left. At each iteration, we compute the new array newNums
by applying the given operation (nums[i] + nums[i+1]) % 10
to each pair of adjacent elements. We then replace the original array nums
with newNums
and continue the process. Finally, when there is only one element left in the array, we return that element as the triangular sum.
- Time complexity: O(n^2) where n is the number of elements in the input array.
- Space complexity: O(n) for the new array created at each iteration.
:
Solutions
class Solution {
public int findTriangularSum(int[] nums) {
while(nums.length > 1) {
int[] newNums = new int[nums.length - 1];
for(int i = 0; i < nums.length - 1; i++) {
newNums[i] = (nums[i] + nums[i+1]) % 10;
}
nums = newNums;
}
return nums[0];
}
}
Loading editor...