LeetCode 910: Smallest Range II Solution
Master LeetCode problem 910 (Smallest Range II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To minimize the score of the array after modifying each element by adding or subtracting k, we need to sort the array first. By sorting the array, we can determine the optimal position to add or subtract k to minimize the difference between the maximum and minimum elements.
- Sort the array.
- Iterate through each element and consider two cases:
- Add
kto all elements starting from the current element to the end. - Subtract
kfrom all elements from the beginning to the current element.
- Add
- Calculate the difference between the maximum and minimum elements after each operation to find the minimum score.
The time complexity of this approach is O(nlogn) due to sorting, and the space complexity is O(1).
Solution Code
class Solution {
public int smallestRangeII(int[] nums, int k) {
Arrays.sort(nums);
int n = nums.length;
int minScore = nums[n - 1] - nums[0];
for (int i = 0; i < n - 1; i++) {
int max = Math.max(nums[i] + k, nums[n - 1] - k);
int min = Math.min(nums[0] + k, nums[i + 1] - k);
minScore = Math.min(minScore, max - min);
}
return minScore;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 910 (Smallest Range II)?
This page provides optimized solutions for LeetCode problem 910 (Smallest Range II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 910 (Smallest Range II)?
The time complexity for LeetCode 910 (Smallest Range II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 910 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 910 in Java, C++, or Python.