36 lines
923 B
C++
36 lines
923 B
C++
#include <algorithm>
|
|
#include <cassert>
|
|
#include <numeric>
|
|
#include <vector>
|
|
|
|
class Solution {
|
|
public:
|
|
std::vector<int> getSumAbsoluteDifferences(const std::vector<int> &nums) {
|
|
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;
|
|
}
|