diff --git a/cpp/2305/LC230508.cpp b/cpp/2305/LC230508.cpp new file mode 100644 index 0000000..319729d --- /dev/null +++ b/cpp/2305/LC230508.cpp @@ -0,0 +1,21 @@ +#include + +/** + * 1572. Matrix Diagonal Sum + * + * Given a square matrix mat, return the sum of the matrix diagonals. + * Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. + */ + +class LC230508 { +public: + static int diagonalSum(const std::vector>&) noexcept; +}; + +int LC230508::diagonalSum(const std::vector>& mat) noexcept { + const int n = mat.size(); + int ret = 0; + for (int i = 0; i < n; ++i) + ret += mat[i][i] + mat[i][n - 1 - i]; + return ret - (n & 1 ? mat[n >> 1][n >> 1] : 0); +} diff --git a/cpp/2305/defs.h b/cpp/2305/defs.h index 60deb48..f7aa0a3 100644 --- a/cpp/2305/defs.h +++ b/cpp/2305/defs.h @@ -75,4 +75,9 @@ public: static std::vector longestObstacleCourseAtEachPosition(const std::vector&) noexcept; }; +class LC230508 { +public: + static int diagonalSum(const std::vector>&) noexcept; +}; + #endif //LEETCODE_CPP_DEFS_H