#2567
Minimum Score by Changing Two Elements
MediumArrayGreedySortingSortingGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n² * m), where m is the range of values in nums. | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
To minimize the score, we can focus on changing the minimum and maximum values in the array. By adjusting these values, we can directly influence both the low and high scores effectively.
⚙️
Algorithm
4 steps- 1Step 1: Find the current minimum and maximum values in the array.
- 2Step 2: Calculate the current low and high scores.
- 3Step 3: Change the minimum value to the second minimum and the maximum value to the second maximum.
- 4Step 4: Calculate the new low and high scores and return their sum.
solution.py3 lines
1def minimumScore(nums):
2 nums.sort()
3 return (nums[-1] - nums[1]) + (nums[-2] - nums[0])ℹ
Complexity note: The optimal solution sorts the array, which takes O(n log n) time, and then performs constant-time operations to calculate the score.
- 1Changing the minimum and maximum values directly influences the score.
- 2Sorting the array allows easy access to the minimum and maximum values.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.