Skip to content

2221. Find Triangular Sum of an Array 👍

  • Time: $O(n)$
  • Space: $O(n)$
1
2
3
4
5
6
7
8
9
class Solution {
 public:
  int triangularSum(vector<int>& nums) {
    for (int sz = nums.size(); sz > 0; --sz)
      for (int i = 0; i + 1 < sz; ++i)
        nums[i] = (nums[i] + nums[i + 1]) % 10;
    return nums[0];
  }
};
1
2
3
4
5
6
7
8
class Solution {
  public int triangularSum(int[] nums) {
    for (int sz = nums.length; sz > 0; --sz)
      for (int i = 0; i + 1 < sz; ++i)
        nums[i] = (nums[i] + nums[i + 1]) % 10;
    return nums[0];
  }
}
1
2
3
4
5
6
class Solution:
  def triangularSum(self, nums: List[int]) -> int:
    for sz in range(len(nums), 0, -1):
      for i in range(sz - 1):
        nums[i] = (nums[i] + nums[i + 1]) % 10
    return nums[0]