To maximize the score, always pair the largest two numbers available, as their difference will be the largest possible at each step. This greedy approach ensures the sum of differences is maximized.
classSolution {
public:int maxScore(vector<int>& nums) {
sort(nums.rbegin(), nums.rend());
int ans =0;
for (int i =0; i < nums.size(); i +=2) {
ans += nums[i] - nums[i+1];
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
classSolution {
publicintmaxScore(int[] nums) {
Arrays.sort(nums);
int ans = 0;
for (int i = nums.length- 1; i > 0; i -= 2) {
ans += nums[i]- nums[i-1];
}
return ans;
}
}
1
2
3
4
5
6
7
classSolution:
defmaxScore(self, nums: list[int]) -> int:
nums.sort(reverse=True)
ans =0for i in range(0, len(nums), 2):
ans += nums[i] - nums[i+1]
return ans