2023-11-25 23:09:33 +01:00
|
|
|
#include <algorithm>
|
|
|
|
#include <cassert>
|
|
|
|
#include <numeric>
|
|
|
|
#include <vector>
|
|
|
|
|
|
|
|
class Solution {
|
2024-01-03 12:06:42 +01:00
|
|
|
public:
|
|
|
|
std::vector<int> getSumAbsoluteDifferences(const std::vector<int> &nums) {
|
2023-11-25 23:09:33 +01:00
|
|
|
auto total = std::accumulate(nums.begin(), nums.end(), 0);
|
|
|
|
|
|
|
|
auto left = 0;
|
|
|
|
std::vector<int> 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;
|
|
|
|
}
|