Skip to content

Commit 8e3628a

Browse files
committed
chore: sync automated leetcode submissions with Runtime - 84 ms (98.67%), Memory - 107.9 MB (67.44%)
1 parent 2f629fd commit 8e3628a

1 file changed

Lines changed: 22 additions & 6 deletions

File tree

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,26 @@
1+
#include <vector>
2+
#include <algorithm>
3+
4+
static const int fast_io = []() {
5+
std::ios_base::sync_with_stdio(false);
6+
std::cin.tie(NULL);
7+
return 0;
8+
}();
9+
110
class Solution {
211
public:
3-
long long maximumHappinessSum(vector<int>& a, int k) {
4-
long long res = 0, i;
5-
sort(a.begin(), a.end());
6-
reverse(a.begin(), a.end());
7-
for (i = 0; i < k; ++i) res += max(0LL, a[i] - i);
8-
return res;
12+
long long maximumHappinessSum(std::vector<int>& happiness, int k) {
13+
std::nth_element(happiness.begin(), happiness.begin() + k, happiness.end(), std::greater<int>());
14+
std::sort(happiness.begin(), happiness.begin() + k, std::greater<int>());
15+
16+
long long totalHappiness = 0;
17+
for (int i = 0; i < k; ++i) {
18+
int currentHappiness = happiness[i] - i;
19+
if (currentHappiness <= 0) break;
20+
21+
totalHappiness += currentHappiness;
22+
}
23+
24+
return totalHappiness;
925
}
1026
};

0 commit comments

Comments
 (0)