Solution
Method-1:
All possible answers are in the form sum * B[i]
, we can iterate all B[i]
increasingly (now, the corresponding B
of all elements insum
must
≥
B
[
i
]
\geq B[i]
≥B[i]);
This is feasible, but complicated;
@Delimiter
The above method is based on iterating B[i]
increasingly, we can do that decreasingly;
When we at B[i]
, let multiset S
be all elements whose B[]
are
≥
B
[
i
]
\geq B[i]
≥B[i], we choose the Greatest-K elements of
S
S
S;
Code
long long maxScore(vector<int>& A, vector<int>& B, int K) {
int n = A.size();
vector< int> ind( n);
for( int i = 0; i < n; ++i) ind[ i] = i;
sort( ind.begin(), ind.end(), [&]( int _a, int _b) -> bool{ return B[ _a] > B[ _b];});
long long ans = 0;
priority_queue< int, vector<int>, greater<int> > Heap;
long long sum = 0;
for( int i = 0; i < n; ++i){
int ii = ind[ i];
Heap.push( A[ ii]);
sum += A[ ii];
if( Heap.size() > K){
sum -= Heap.top();
Heap.pop();
}
if( Heap.size() == K){
ans = max( sum * B[ ii], ans);
}
}
return ans;
}