Max-Min Sum of N-M Elements
EasyP3Coding
You are given an array nums of n integers and an integer m with 0 <= m <= n.
Consider the n - m largest elements and the n - m smallest elements (counted with multiplicity). Return the sum of the largest ones minus the sum of the smallest ones. If m == n, both groups are empty and the answer is 0.
Example 1
- Input
- nums = [1,2,3,4,5], m = 2
- Output
- 6
- Why
- Largest 3: 3+4+5 = 12. Smallest 3: 1+2+3 = 6. 12 - 6 = 6.
Example 2
- Input
- nums = [5,1,5,1], m = 1
- Output
- 4
- Why
- Largest 3: 5+5+1 = 11. Smallest 3: 1+1+5 = 7. 11 - 7 = 4.
Example 3
- Input
- nums = [4,4,4], m = 0
- Output
- 0
Constraints
- 1 <= nums.length <= 1000
- 0 <= m <= nums.length
- -10^4 <= nums[i] <= 10^4
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 9. ⌘Enter runs, ⌘⇧Enter submits.