There are n sticks with some lengths. Your task is to modify the sticks so that each stick has the same length.
You can either lengthen and shorten each stick. Both operations cost x where x is the difference between the new and original length.
What is the minimum total cost?
Example:
Input: n = 5, arr = {2, 3, 1, 5, 2}
Output: 5
Approach
C++
#include <bits/stdc++.h>using namespace std;long long stickLengths(long long n,vector<long long> &arr){sort(arr.begin(), arr.end());long long med = arr[n / 2];long long ans = 0;for (long long x : arr){ans += abs(x - med);}return ans;}int main(){long long n = 5;vector<long long> arr = {2, 3, 1, 5, 2};cout << stickLengths(n, arr) << "\n";return 0;}
No comments:
Post a Comment