908. Smallest Range I LeetCode Solution

In this guide, you will get 908. Smallest Range I LeetCode Solution with the best time and space complexity. The solution to Smallest Range I problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Smallest Range I solution in C++
  4. Smallest Range I solution in Java
  5. Smallest Range I solution in Python
  6. Additional Resources
908. Smallest Range I LeetCode Solution image

Problem Statement of Smallest Range I

You are given an integer array nums and an integer k.
In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k]. You can apply this operation at most once for each index i.
The score of nums is the difference between the maximum and minimum elements in nums.
Return the minimum score of nums after applying the mentioned operation at most once for each index in it.

Example 1:

Input: nums = [1], k = 0
Output: 0
Explanation: The score is max(nums) – min(nums) = 1 – 1 = 0.

Example 2:

Input: nums = [0,10], k = 2
Output: 6
Explanation: Change nums to be [2, 8]. The score is max(nums) – min(nums) = 8 – 2 = 6.

Example 3:

Input: nums = [1,3,6], k = 3
Output: 0
Explanation: Change nums to be [4, 4, 4]. The score is max(nums) – min(nums) = 4 – 4 = 0.

Constraints:

1 <= nums.length <= 104
0 <= nums[i] <= 104
0 <= k <= 104

Complexity Analysis

  • Time Complexity:
  • Space Complexity:
See also  1220. Count Vowels Permutation LeetCode Solution

908. Smallest Range I LeetCode Solution in C++

class Solution {
 public:
  int smallestRangeI(vector<int>& nums, int k) {
    const int mx = ranges::max(nums);
    const int mn = ranges::min(nums);
    return max(0, mx - mn - 2 * k);
  }
};
/* code provided by PROGIEZ */

908. Smallest Range I LeetCode Solution in Java

class Solution {
  public int smallestRangeI(int[] nums, int k) {
    final int mx = Arrays.stream(nums).max().getAsInt();
    final int mn = Arrays.stream(nums).min().getAsInt();
    return Math.max(0, mx - mn - 2 * k);
  }
}
// code provided by PROGIEZ

908. Smallest Range I LeetCode Solution in Python

class Solution:
  def smallestRangeI(self, nums: list[int], k: int) -> int:
    return max(0, max(nums) - min(nums) - 2 * k)
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.