diff --git a/problems/cpp/sum-of-absolute-differences-in-a-sorted-array.cpp b/problems/cpp/sum-of-absolute-differences-in-a-sorted-array.cpp new file mode 100644 index 0000000..7d7e49b --- /dev/null +++ b/problems/cpp/sum-of-absolute-differences-in-a-sorted-array.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +#include + +class Solution { + public: + std::vector getSumAbsoluteDifferences(const std::vector& nums) { + auto total = std::accumulate(nums.begin(), nums.end(), 0); + + auto left = 0; + std::vector result; + for (auto i = 0u; i < nums.size(); ++i) { + auto left_diff = i * nums[i] - left; + + auto right = total - nums[i] - left; + auto right_diff = right - (nums.size() - i - 1) * nums[i]; + + result.push_back(left_diff + right_diff); + + left += nums[i]; + } + + return result; + } +}; + +int main() { + Solution s; + + assert((s.getSumAbsoluteDifferences(std::vector{2, 3, 5}) == + std::vector{4, 3, 5})); + assert((s.getSumAbsoluteDifferences(std::vector{1, 4, 6, 8, 10}) == + std::vector{24, 15, 13, 15, 21})); + return 0; +}