You are given an array A of N integers. You want to choose some integers from the array subject to the condition that the number of distinct integers chosen should not exceed
. Your task is to maximize the sum of chosen numbers.
Example:
Input: n = 4, k = 2, arr = {2, 1, 2, 5}
Output: 9
Approach
C++
#include <bits/stdc++.h>using namespace std;long long maximizeTheSum(int n, int k, vector<long long> arr){unordered_map<long long, long long> m;for (int j = 0; j < n; j++){m[arr[j]] += arr[j];}priority_queue<long long> q;for (auto &it : m){q.push(it.second);}if (q.size() == 0){return 0;}long long sum = 0;while (q.size() && k >= 1){sum += q.top();q.pop();k--;}sum = max(sum, 0LL);return sum;}int main(){ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);int n = 4, k = 2;vector<long long> arr = {2, 1, 2, 5};cout << maximizeTheSum(n, k, arr) << "\n";return 0;}
No comments:
Post a Comment