Skip to content

Commit e3a7261

Browse files
authored
Create 3075. Maximize Happiness of Selected Children (#475)
2 parents cdea173 + 20ed7a1 commit e3a7261

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
public:
3+
long long maximumHappinessSum(vector<int>& happiness, int k) {
4+
// Sort the vector in ascending order
5+
std::sort(happiness.begin(), happiness.end());
6+
7+
// Reverse the vector to get descending order
8+
std::reverse(happiness.begin(), happiness.end());
9+
10+
int selected = 0;
11+
long long happinessScore = 0; // Use long long to handle larger sums
12+
13+
// Iterate over the sorted happiness values
14+
for (int score : happiness) {
15+
if (selected == k) {
16+
break; // Stop if 'k' elements have been selected
17+
}
18+
// Calculate and add the adjusted happiness value if it's positive
19+
happinessScore += std::max(0, score - selected);
20+
selected++;
21+
}
22+
23+
return happinessScore;
24+
}
25+
};

0 commit comments

Comments
 (0)