-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path09may.txt
33 lines (28 loc) · 1 KB
/
09may.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public long maximumHappinessSum(int[] happiness, int k) {
// Sort the array in ascending order
Arrays.sort(happiness);
// Reverse the array to get descending order
reverseArray(happiness);
int selected = 0;
long happinessScore = 0; // Changed to 'long' to handle larger sums
// Iterate over the sorted happiness values
for (int score : happiness) {
if (selected == k) {
break; // Stop if 'k' elements have been selected
}
// Calculate and add the adjusted happiness value if it's positive
happinessScore += Math.max(0, score - selected);
selected++;
}
return happinessScore;
}
// Helper method to reverse the array
private void reverseArray(int[] array) {
for (int i = 0, j = array.length - 1; i < j; i++, j--) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}