Sum of upper and lower triangles

PHOTO EMBED

Tue Feb 08 2022 08:14:36 GMT+0000 (Coordinated Universal Time)

Saved by @Uttam #java #gfg #geeksforgeeks #2d #array #matrix #practice #sum

class Solution
{
    //Function to return sum of upper and lower triangles of a matrix.
    static ArrayList<Integer> sumTriangles(int matrix[][], int n)
    {
        ArrayList<Integer> list=new ArrayList<>();
        int sum1=0;
        int sum2=0;
        for(int g=0; g<matrix.length; g++){
            for(int i=0, j=g; j<matrix.length; i++,j++){
                sum1+=matrix[i][j];
            }
        }
        list.add(sum1);
        for(int g=0; g<matrix.length; g++){
            for(int i=g,j=0; i<matrix.length; i++,j++){
                sum2+=matrix[i][j];
            }
        }
        list.add(sum2);
        return list;
    }
}
content_copyCOPY

Sum of upper and lower triangles Given a square matrix of size N*N, print the sum of upper and lower triangular elements. Upper Triangle consists of elements on the diagonal and above it. The lower triangle consists of elements on the diagonal and below it. Example 1: Input: N = 3 mat[][] = {{6, 5, 4}, {1, 2, 5} {7, 9, 7}} Output: 29 32 Explanation: The given matrix is 6 5 4 1 2 5 7 9 7 The elements of upper triangle are 6 5 4 2 5 7 Sum of these elements is 6+5+4+2+5+7=29 The elements of lower triangle are 6 1 2 7 9 7 Sum of these elements is 6+1+2+7+9+7= 32. Example 2: Input: N = 2 mat[][] = {{1, 2}, {3, 4}} Output: 7 8 Explanation: Upper triangular matrix: 1 2 4 Sum of these elements are 7. Lower triangular matrix: 1 3 4 Sum of these elements are 8. Your Task: You don't need to read input or print anything. Complete the function sumTriangles() that takes matrix and its size N as input parameters and returns the list of integers containing the sum of upper and lower triangle. Expected Time Complexity: O(N * N) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 100 1 <= matrix[i][j] <= 100

https://practice.geeksforgeeks.org/problems/sum-of-upper-and-lower-triangles-1587115621/1/?track=DSASP-Matrix&batchId=190