problems(cpp): add “1685. Sum of Absolute Differences in a Sorted Array”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
43e0ba224d
commit
ea77054424
1 changed files with 36 additions and 0 deletions
|
@ -0,0 +1,36 @@
|
||||||
|
#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;
|
||||||
|
}
|
Loading…
Reference in a new issue