Give an integer array a1,a2,...,an and an integer k. If you can either make ai=ai−1 or ai=aj, what is the minimum number of steps you need to make the sum of array ∑ni=1ai<=k?
Let's do it in a greedy way. Sort the array in an non-deceasing order. Apply operation one on a1 x times and apply operation two from an y times. The final array would look like (a1−x),a2,a3,...,an−y,(a1−x),(a1−x),...,(a1−x). So we need to minimize the value of x+y and we need (a1−x)∗(y+1)+pref(n−y)−a1<=k where pref is the prefix sum which can be precomputed beforehand. Rearrange it to get the minimum possible x by iterating y ,
x=a1−⌊k−pref(n−y)+a1y+1⌋
Solution:
long long safe_floor(long long x, long long y) {
long long res = x / y;
while (res * y > x) res--;
return res;
}
void solve() {
long long n, k; cin >> n >> k;
vector<long long> a(n);
long long sum = 0;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
sort(a.begin(), a.end());
vector<long long> pref(n + 1);
for (int i = 0; i < n; i++) {
pref[i + 1] = pref[i] + a[i];
}
long long ans = 9e18;
for (int y = 0; y < n; y++) {
long long x = a[0] - safe_floor(k - pref[n - y] + a[0], y + 1);
x = max(0LL, x);
ans = min(ans, x + y);
}
cout << ans << endl;
}
No comments:
Post a Comment