LeetCode 908: Smallest Range I Solution
Master LeetCode problem 908 (Smallest Range I), a easy 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 nums after applying the operation, we need to make the range of values in nums as small as possible. We can achieve this by adjusting the elements in nums to bring them closer together. Since we can only change each element once within the range [-k, k], the optimal strategy is to increase the minimum values and decrease the maximum values. This will reduce the overall difference between the maximum and minimum elements, thus minimizing the score.
To calculate the minimum score after applying the operation, we need to find the current range of values in nums and check if it can be reduced by at most 2k. If the current range is already smaller than 2k, the minimum score will be 0. Otherwise, we can reduce the range by 2*k to minimize the score.
- Time complexity: O(n) where n is the length of the input array nums.
- Space complexity: O(1)
Solution Code
class Solution {
public int smallestRangeI(int[] nums, int k) {
int minNum = nums[0];
int maxNum = nums[0];
for (int num : nums) {
minNum = Math.min(minNum, num);
maxNum = Math.max(maxNum, num);
}
int diff = maxNum - minNum - 2 * k;
return diff > 0 ? diff : 0;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 908 (Smallest Range I)?
This page provides optimized solutions for LeetCode problem 908 (Smallest Range I) 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 908 (Smallest Range I)?
The time complexity for LeetCode 908 (Smallest Range I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 908 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 908 in Java, C++, or Python.